先来看一下我一开始的愚蠢的做法
public class Solution1 {
public static List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> ret = new ArrayList<>();
for(String str:strs){
boolean find = false;
for(int i = 0;i<ret.size();i++){
if(check(str,ret.get(i).get(0))){
ret.get(i).add(str);
find = true;
break;
}
}
if(!find){
List<String> newList = new ArrayList<>();
newList.add(str);
ret.add(newList);
}
}
return ret;
}
private static boolean check(String s1,String s2){
if(s1.length() != s2.length())return false;
char[] c1=s1.toCharArray();
char[] c2 = s2.toCharArray();
Arrays.sort(c2);
Arrays.sort(c1);
for(int i = 0 ; i < c1.length;i++){
if(c1[i]!=c2[i])return false;
}
return true;
}
}
优化后
public class Solution2 {
public List<List<String>> groupAnagrams(String[] strs) {
if (strs.length == 0) return new ArrayList();
List<List<String>> ret = new ArrayList<>();
Map<String, List> map = new HashMap<>();
for (String str : strs) {
char[] chars=str.toCharArray();
Arrays.sort(chars);
String key = new String(chars);
if (map.containsKey(key)) {
map.get(key).add(str);
} else {
ArrayList<String> list =new ArrayList();
list.add(str);
map.put(key,list );
ret.add(list);
}
}
return ret;
}
}