LeetCode开心刷题二十六天——49.Group Anagrams
Posted marigolci
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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))
以上是关于LeetCode开心刷题二十六天——49.Group Anagrams的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode开心刷题二十九天——63. Unique Paths II**
LeetCode开心刷题十六天——29. Divide Two Integers*