Skip to content

Commit

Permalink
[String] Refactor solution to Group Anagrams
Browse files Browse the repository at this point in the history
  • Loading branch information
soapyigu authored Nov 1, 2019
1 parent e340e8b commit 2b79ccd
Showing 1 changed file with 8 additions and 13 deletions.
21 changes: 8 additions & 13 deletions String/GroupAnagrams.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,25 +2,20 @@
* 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)
* Time Complexity: O(nmlogm), 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]]()
var sortedStrToStrs = [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

sortedStrToStrs[sortedStr, default: []].append(str)
}

return map.values.map { value in value.sorted() }
return Array(sortedStrToStrs.values)
}
}
}

0 comments on commit 2b79ccd

Please sign in to comment.