When argument is null , the String.valueOf returns "null" ,
but Object.toString throws NullPointerException , that's the only difference.
public List<String> anagrams(String[] strs) {
List<String> result=new ArrayList<String>();
if(strs==null || strs.length==0){
return result;
}
HashMap<String,List<String>> map=new HashMap<>();
for(int i=0;i<strs.length;i++){
//fetch this word and make it array then sort it then remake a string
char[] current=strs[i].toCharArray();
Arrays.sort(current);
//不能用 String key=current.toString();
//或者String key=String.valueOf(current);
String key=new String(current);
if(map.containsKey(key)){
map.get(key).add(strs[i]);
}else{
List<String> word=new ArrayList<String>();
word.add(strs[i]);
map.put(key, word);
}
}
for(List<String> element:map.values()){
if(element.size()>1){
result.addAll(element);
}
}
return result;
}
Version 2: 为每一个单词建立一个hash值,用hash值存放进hashmap.
private int getHash(int[] count) {
int hash = 0;
int a = 378551;
int b = 63689;
for (int num : count) {
hash = hash * a + num;
a = a * b;
}
return hash;
}
public ArrayList<String> anagrams(String[] strs) {
ArrayList<String> result = new ArrayList<String>();
HashMap<Integer, ArrayList<String>> map = new HashMap<Integer, ArrayList<String>>();
for (String str : strs) {
int[] count = new int[26];
for (int i = 0; i < str.length(); i++) {
count[str.charAt(i) - 'a']++;
}
int hash = getHash(count);
if (!map.containsKey(hash)) {
map.put(hash, new ArrayList<String>());
}
map.get(hash).add(str);
}
for (ArrayList<String> tmp : map.values()) {
if (tmp.size() > 1) {
result.addAll(tmp);
}
}
return result;
}