标签:
将所含字母相同,但排列顺序不同的字符串归并到一起。
注意点:
例子:
输入: strs = [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”]
输出: [
[“ate”, “eat”,”tea”],
[“nat”,”tan”],
[“bat”]
]
将每个字符串排序,并把排序后相同的字符串归为一组,将每组字符串排序后即为所要的结果。
class Solution(object):
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
map = {}
for i, v in enumerate(strs):
target = "".join(sorted(v))
if target not in map:
map[target]=[v]
else:
map[target].append(v)
result = []
for value in map.values():
result += [sorted(value)]
return result
if __name__ == "__main__":
assert Solution().groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"]) == [[‘nat‘, ‘tan‘], [‘bat‘],
[‘ate‘, ‘eat‘, ‘tea‘]]
欢迎查看我的Github来获得相关源码。
标签:
原文地址:http://blog.csdn.net/u013291394/article/details/50486985