Wednesday, January 22, 2014

Anagrams LeetCode

把每个词汇的字母进行排序,然后当做Key,放到HashMap中,实现很容易。
开始以为每个group存到一个ArrayList里面呢。

public ArrayList<String> anagrams(String[] strs) {
        ArrayList<String> result = new ArrayList<String>();
        HashMap<String, ArrayList<String>> hm = new HashMap<String, ArrayList<String>>();
for (String str : strs){
char[] chars = str.trim().toCharArray();
Arrays.sort(chars);
String key = new String(chars);

if (hm.containsKey(key)){
hm.get(key).add(str);
} else {
ArrayList<String> temp = new ArrayList<String>();
temp.add(str);
hm.put(key, temp);
}
}

for (ArrayList<String> group : hm.values()){
if (group.size()>1){
result.addAll(group);
}
}
return result;
    }

No comments:

Post a Comment