1.结果用hashMap保存
2.遍历字符数组中每一个字符串
3.把字符串转成字符数组并排序
4.判断hashmap中是否存在 并加入到map中
5.返回hashmap中所有value
实现代码:
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
if (strs.length == 0 || strs == null) {
return null;
}
Map<String, List> res = new HashMap<>();
for (String c : strs) {
char[] tmp = c.toCharArray();
Arrays.sort(tmp);
String key = new String(tmp);
if (!res.containsKey(key)) {
res.put(key, new ArrayList<String>());
}
res.get(key).add(c);
}
return new ArrayList(res.values());
}
}