天天看點

leetcode 字母異位詞分組 python3

給定一個字元串數組,将字母異位詞組合在一起。字母異位詞指字母相同,但排列不同的字元串。

示例:

輸入: ["eat", "tea", "tan", "ate", "nat", "bat"]
輸出:
[
  ["ate","eat","tea"],
  ["nat","tan"],
  ["bat"]
]
           

說明:

所有輸入均為小寫字母。

不考慮答案輸出的順序。

思路一:利用哈希表減少運算時間。

python中使用”字典“維護一個分組表,鍵值(key)為排序後的字元串,值(value)為子分組的下标

result=[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
           

每次對字元串排序後加入對應的分組中,或者建立新的分組

class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        newstrs = []
        group = {}
        for i in range(len(strs)):
            temp_list = list(strs[i])
            temp_list.sort()
            sorted_string="".join(temp_list)
            if sorted_string in group:
                newstrs[group[sorted_string]].append(strs[i])
            else:
                group[sorted_string] = len(group)
                newstrs.append([strs[i]])
        return newstrs