public List<String> anagrams(String[] strs) {
List<String> res = new ArrayList<String>();
if (strs==null || strs.length==0) return res;
HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
for (int i=0; i<strs.length; i++) {
char[] charArr = strs[i].toCharArray();
Arrays.sort(charArr);
String key = new String(charArr);
if (map.containsKey(key)) {
map.get(key).add(strs[i]);
} else {
ArrayList<String> list = new ArrayList<String>();
list.add(strs[i]);
map.put(key, list);
}
}
for (ArrayList<String> x : map.values()) {
if (x.size()>1) res.addAll(x);
}
return res;
}
No comments:
Post a Comment