將所含字母相同,但排列順序不同的字符串歸並到一起。
注意點:
所有輸入的字符都是小寫的 返回結果中每個組的字符串都要按照字典序排列例子:
輸入: 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']]