一、 问题描述:
Given an array of strings, groupanagrams together.
Example:
Input:["eat", "tea", "tan","ate", "nat", "bat"],
Output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
Note:
- All inputs will be in lowercase.
- The order of your output does not matter
二、 问题分析:
给定一个元素为字符串的列表,要求把具有相同字符不同排序方法的字符串归类在同一列表,输出元素为字符串归类列表的列表。
例如题目所给的样例:
["eat", "tea", "tan", "ate","nat", "bat"]
因为"ate","eat","tea" 具有相同字符但字符排序方法不同,所以将它们归类在同一列表:["ate","eat","tea"]
同样,"tan" 和 "nat" 也属于相同字符不同排列顺序,所以也将它们归类在同一列表:["nat","tan"]
而最后只剩下 "bat" 唯一一个元素,所以将它单独归类为一个列表:["bat"]
因此,最后输出列表为:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
三、 算法设计:
假设输入列表为q,定义一个字典d,对q中的每个字符串str元素进行以下操作:
对str进行字典顺序排序获得新字符串nstr,在d中搜索是否存在以nstr为键,值为列表的元素:①如果存在,则将str加入该列表中;②如果不存在,则在d中创建一个以nstr为键,值为仅包含str的列表的元素
返回d的值列表,即为目的结果:元素为字符串归类列表的列表
四、 程序实现:
class Solution:
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
n = len(strs)
strss = []
dic = {}
for s in strs:
temp = list(s);
temp.sort()
temp = ''.join(temp)
if temp not in dic.keys():
dic[temp] = [s]
else:
dic[temp].append(s)
return list(dic.values())