Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
public class Solution {
public ArrayList<String> anagrams(String[] strs) {
HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
ArrayList<String> ret = new ArrayList<String>();
for(int i=0;i<strs.length;i++) {
String str = strs[i];
char[] chars = str.trim().toCharArray();
Arrays.sort(chars);
String key = new String(chars);
ArrayList<String> val = map.get(key);
if(val==null) {
val = new ArrayList<String>();
map.put(key, val);
}
val.add(str);
}
for(String key : map.keySet()) {
if(map.get(key).size()>1) {
ret.addAll(map.get(key));
}
}
return ret;
}
}
没有评论:
发表评论