1. 程式人生 > >Leetcode題庫——49.字母異位詞分組

Leetcode題庫——49.字母異位詞分組

imp lis upa 一個 字典 最終 __init__ software clas


@author: ZZQ
@software: PyCharm
@file: leetcode49_groupAnagrams.py
@time: 2018/11/19 13:18
要求:給定一個字符串數組,將字母異位詞組合在一起。字母異位詞指字母相同,但排列不同的字符串。
示例:
輸入: ["eat", "tea", "tan", "ate", "nat", "bat"],
輸出:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
說明:
所有輸入均為小寫字母。
不考慮答案輸出的順序。
思路:ans用一個字典來表示,字典的鍵值是由26個字母組成的數組,來存儲當前單詞的哈希映射,值則是對應的這個單詞。
最終的輸出是ans的值。


import collections


class Solution():
    def __init__(self):
        pass

    def groupAnagrams(self, strs):
        ans = collections.defaultdict(list)
        for s in strs:
            count = [0] * 26
            for c in s:
                count[ord(c) - ord(‘a‘)] += 1
            ans[tuple(count)].append(s)
        return ans.values()

Leetcode題庫——49.字母異位詞分組