From 2b79ccd2e6e4690d3aa45f0df6b972e628f40352 Mon Sep 17 00:00:00 2001 From: Soap Date: Thu, 31 Oct 2019 19:54:14 -0700 Subject: [PATCH] [String] Refactor solution to Group Anagrams --- String/GroupAnagrams.swift | 21 ++++++++------------- 1 file changed, 8 insertions(+), 13 deletions(-) diff --git a/String/GroupAnagrams.swift b/String/GroupAnagrams.swift index ffb476d2..08ab82f2 100644 --- a/String/GroupAnagrams.swift +++ b/String/GroupAnagrams.swift @@ -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) } -} \ No newline at end of file +}