-
Notifications
You must be signed in to change notification settings - Fork 21
/
GroupAnagrams.swift
49 lines (43 loc) 路 1.08 KB
/
GroupAnagrams.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
//
// GroupAnagrams.swift
// LeetCode
//
// Created by 榛庤档澶儙 on 26/11/2017.
// Copyright 漏 2017 lizhaotailang. All rights reserved.
//
// Given an array of strings, group anagrams together.
//
// For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"],
// Return:
//
// [
// ["ate", "eat","tea"],
// ["nat","tan"],
// ["bat"]
// ]
// Note: All inputs will be in lower-case.
//
// Accepted. See [GroupAnagramsTests](./LeetCodeTests/GroupAnagramsTests.swift) for test cases.
//
import Foundation
class GroupAnagrams {
func groupAnagrams(_ strs: [String]) -> [[String]] {
var results: [[String]] = []
if strs.isEmpty {
return results
}
var map: [String: [String]] = [:]
for s in strs {
let chars = Array(s)
let key = String(chars.sorted())
if map[key] == nil {
map[key] = []
}
map[key]?.append(s)
}
for array in map.values {
results.append(array)
}
return results
}
}