forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
GroupAnagrams.swift
41 lines (35 loc) · 1.22 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
/**
* Question Link: https://leetcode.com/problems/anagrams/
* Primary idea: Iterate the string array and categories strings with the same sorted one
*
* Time Complexity: O(nmlogm + nlogn), n stands for number of words, m stands for the length of a word
* Space Complexity: O(n)
*/
class GroupAnagrams {
func groupAnagrams(strs: [String]) -> [[String]] {
var res = [[String]]()
var map = [String: [String]]()
for str in strs {
let sortedStr = _sortStr(str)
var anagrams = [String]()
if map[sortedStr] != nil {
anagrams = map[sortedStr] as [String]!
}
anagrams.append(str)
map[sortedStr] = anagrams
}
_convertMapToLists(map, &res)
return res
}
private func _sortStr(str: String) -> String {
var strChars = [Character](str.characters)
strChars.sortInPlace({$0 < $1})
return String(strChars)
}
private func _convertMapToLists(map: [String: [String]], inout _ res: [[String]]) {
for anagrams in map.values {
let anagrams = anagrams.sort({$0 < $1})
res.append(anagrams)
}
}
}