Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
Use a map to store sortedWord -> its anagrams.
public List<String> anagrams(String[] strs) {
List<String> results = new ArrayList<String>();
if (strs==null||strs.length==0) {
return results;
}
Map<String, List<String>> table = new HashMap<String, List<String>>();
for (String str : strs) {
char[] array = str.toCharArray();
Arrays.sort(array);
String sortedStr = String.valueOf(array);
List<String> anagrams = table.get(sortedStr);
if (anagrams==null) {
anagrams = new ArrayList<String>();
table.put(sortedStr, anagrams);
}
anagrams.add(str);
}
for (String key : table.keySet()) {
List<String> anagrams = table.get(key);
if (anagrams.size()>1) {
results.addAll(anagrams);
}
}
return results;
}