14 - Medium - 字謎分組

給定一個字符串?dāng)?shù)組,將字母異位詞組合在一起。字母異位詞指字母相同,但排列不同的字符串。

示例:

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

所有輸入均為小寫字母。
不考慮答案輸出的順序。

關(guān)鍵:字典,key為排序后的字母序,value為return_list的下標

class Solution:
    def groupAnagrams(self, strs):
        """
        :type strs: List[str]
        :rtype: List[List[str]]
        """
        d = {}
        i = 0
        res = []
        for _str in strs:
            temp = "".join(sorted(_str))
            if temp in d:
                res[d[temp]].append(_str)
            else:
                d[temp] = i
                res.append([_str])
                i += 1
        return res

關(guān)鍵:字典

class Solution:
    def groupAnagrams(self, strs):
        """
        :type strs: List[str]
        :rtype: List[List[str]]
        """
        d = {}
        for x in strs:
            key = tuple(sorted(x))
            d[key] = d.get(key,[]) + [x]
        return list(d.values())
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容