LeetCode开心刷题二十六天——49.Group Anagrams

49. Group Anagrams Medium

Given an array of strings, group anagrams together.

Example:

Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
  ["ate","eat","tea"],
  ["nat","tan"],
  ["bat"]
]
bonus:
1.join function usage:
str = "-";
seq = ("a", "b", "c"); # 字符串序列
print str.join( seq );
result:
a-b-c

 

class Solution:
    def groupAnagrams(self, strs):
        res = {}
        for item in strs:
            k = ''.join(sorted(item))  # 字符串排序
            print("k")
            print(k)
            print("sorted")
            print(sorted(item))
            if k not in res:  # 判断是否存在
                res[k] = []
            res[k].append(item)  # 相同字符串放到同一个字典 k中
        return [res[x] for x in res]  # 输出结果


if __name__ == '__main__':
    strs = ['eat', 'tea', 'tan', 'ate', 'nat', 'bat']
    solu = Solution()
    print(solu.groupAnagrams(strs))

 

 
上一篇:[Python]Python的class(类)中的object是什么意思


下一篇:基于虚拟用户的方式使用vsftp