領釦--字母異位詞分組--Python實現
阿新 • • 發佈:2019-01-07
給定一個字串陣列,將字母異位詞組合在一起。字母異位詞指字母相同,但排列不同的字串。 示例: 輸入: ["eat", "tea", "tan", "ate", "nat", "bat"], 輸出: [ ["ate","eat","tea"], ["nat","tan"], ["bat"] ] 說明: 所有輸入均為小寫字母。 不考慮答案輸出的順序。
import collections class Solution: def groupAnagrams(self, strs): """ :type strs: List[str] :rtype: List[List[str]] """ ans = collections.defaultdict(list) for s in strs: ans[tuple(sorted(s))].append(s) return list(ans.values()) object=Solution() list1=["eat", "tea", "tan", "ate", "nat", "bat"] result=object.groupAnagrams(list1) print(result)
執行結果: