标签:for str array medium tle title main bat sorted
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
标签:for str array medium tle title main bat sorted
原文地址:https://www.cnblogs.com/Marigolci/p/11252171.html