版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Apple_hzc/article/details/83239114
一、Description
给定一个字符串数组,将所有字符串中字母相同的字符串放在一个list中,最后返回一个list集合。
举例:
Input: ["eat", "tea", "tan", "ate", "nat", "bat"]
,
Output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
二、Analyzation
对于每一组list,如果将它们按照字母表顺序放进一个int数组中,对应的数组必定是完全相同的,这里可以考虑利用hashCode方法对于每一个字符串生成的字母表数组进行判断,若在map中存在该hashcode对应的list,则直接加入,若没有则新建一个list,并加入到map中。
三、Aceptted code
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> list = new ArrayList<List<String>>();
if (strs == null || strs.length == 0) {
return list;
}
Map<Integer, List<String>> map = new HashMap<>();
for (int i = 0; i < strs.length; i++) {
String s = strs[i];
int[] temp = new int[26];
for (int j = 0; j < s.length(); j++) {
temp[s.charAt(j) - 'a']++;
}
Integer integer = Arrays.hashCode(temp);
if (map.containsKey(integer)) {
List<String> list1 = map.get(integer);
list1.add(s);
map.put(integer, list1);
} else {
List<String> list1 = new ArrayList<>();
list1.add(s);
map.put(integer, list1);
}
}
for (Integer i : map.keySet()) {
list.add(map.get(i));
}
return list;
}
}