Skip to content

Commit f58fd6f

Browse files
committed
46. Group Anagrams
1 parent 7b37311 commit f58fd6f

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ Not only Leetcode solutions in Swift.
66
* [15. 3Sum](https://leetcode.com/problems/3sum/)
77
* [16. 3Sum Closest](https://leetcode.com/problems/3sum-closest/)
88
* [18. 4Sum](https://leetcode.com/problems/4sum/)
9+
* [46. Group Anagrams](https://leetcode.com/problems/anagrams/)
910
* [167. Two Sum II - Input array is sorted](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/)
1011
* [170. Two Sum III - Data structure design](https://leetcode.com/problems/two-sum-iii-data-structure-design)
1112
* [Two Sum - Less than or equal to target](http://www.lintcode.com/en/problem/two-sum-less-than-or-equal-to-target/)

SwiftyLeetCode.playground/Contents.swift

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -200,6 +200,33 @@ let fourSumNums = [1, 0, -1, 0, -2, 2]
200200
let fourSumTarget = 0
201201
Solution.fourSum(nums: fourSumNums, fourSumTarget)
202202

203+
/**
204+
* 49. Group Anagrams
205+
* https://leetcode.com/problems/anagrams/
206+
*/
207+
208+
extension Solution {
209+
class func groupAnagrams(strs: [String]?) -> [[String]]? {
210+
guard let strs = strs, strs.count > 0 else { return nil }
211+
212+
var map = [String: [String]]()
213+
strs.forEach { str in
214+
let kStr = String(str.characters.sorted())
215+
if(map[kStr] == nil) {
216+
map[kStr] = [String]()
217+
}
218+
map[kStr]!.append(str)
219+
}
220+
221+
return Array(Array(map.values))
222+
}
223+
}
224+
225+
// usage
226+
227+
let groupAnagramsStrs = ["eat", "tea", "tan", "ate", "nat", "bat"]
228+
Solution.groupAnagrams(strs: groupAnagramsStrs)
229+
203230
/**
204231
* 167. Two Sum II - Input array is sorted
205232
* https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/

0 commit comments

Comments
 (0)