【Leetcode_總結】49. 字母異位詞分組 - python
阿新 • • 發佈:2019-01-07
Q:
給定一個字串陣列,將字母異位詞組合在一起。字母異位詞指字母相同,但排列不同的字串。
示例:
輸入: ["eat", "tea", "tan", "ate", "nat", "bat"]
,
輸出:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
說明:
- 所有輸入均為小寫字母。
- 不考慮答案輸出的順序。
連結:https://leetcode-cn.com/problems/group-anagrams/description/
思路:因為是易位詞,因此排序後的詞順序是相同的,因此對排序後的詞通過hash map進行儲存,儲存的是其在res中的位置,然後將後續的值插入就可以了
程式碼:
class Solution: def groupAnagrams(self, strs): """ :type strs: List[str] :rtype: List[List[str]] """ strs_map = {} result = [] for i in strs: string = ''.join(sorted(i)) if string not in strs_map: strs_map[string] = len(result) result.append([i]) else: result[strs_map[string]].append(i) return result