forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGroupAnagrams.swift
More file actions
26 lines (22 loc) · 783 Bytes
/
GroupAnagrams.swift
File metadata and controls
26 lines (22 loc) · 783 Bytes
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
/**
* 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 map = [String: [String]]()
for str in strs {
let sortedStr = String(str.sorted())
var anagrams = [String]()
if let list = map[sortedStr] {
anagrams = list
}
anagrams.append(str)
map[sortedStr] = anagrams
}
return map.values.map { value in value.sorted() }
}
}