給定一個字符串數組,將字母異位詞組合在一起。字母異位詞指字母相同,但排列不同的字符串。
示例:
輸入: ["eat", "tea", "tan", "ate", "nat", "bat"]輸出:[ ["ate","eat","tea"], ["nat","tan"], ["bat"]]說明:
所有輸入均為小寫字母。
不考慮答案輸出的順序。
來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/group-anagrams/
Link:https://leetcode.com/problems/group-anagrams/
排序+哈希O(N * KlogK), N等於單詞個數,K等於單詞平均長度
class Solution: def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
seen = {} res = []
for word in strs: sort_word = ''.join(sorted(word)) if sort_word in seen: index = seen[sort_word] res[index].append(word) else: ans = [word] index = len(res) res.append(ans) seen[sort_word] = index
return res哈希O(N * K), 理論上更快一些,python代碼實際並不是
將字符串用數組表示, 例如: "eat"
[a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z] 1 1 1代碼如下:
class Solution: def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
seen = {} res = [] base = ord('a')
for word in strs: word_count = [0 for i in range(26)] for char in word: index = ord(char) - base word_count[index] += 1 word_count = tuple(word_count)
if word_count in seen: index = seen[word_count] res[index].append(word) else: ans = [word] index = len(res) res.append(ans) seen[word_count] = index
return res--End--