Description:
Given an array of strings, return all groups of strings that are anagrams.
Solution:
The description didn't tell us whether we need to find out all the groups of anagrams, so it is better for us to find them all.
Use HashMap <String, ArrayList<String>> as the data structure. The first String can be a representative for all strings in ArrayList<String>, but it is sorted by all chars in it.
Scan all string array. Everytime we meet a string, we turn it into char[] array, then sort it, then turn this char[] array into new string, and use it as a key to search in the HashMap.
After scanning the string array, we then scan the HashMap. If the the size of value ArrayList<String> is bigger than 1, then all strings in this arraylist are anagrams.
import java.util.*;
public class Solution {
ArrayList<String> list = new ArrayList<String>();
TreeMap<String, ArrayList<String>> map = new TreeMap<String, ArrayList<String>>();
public List<String> anagrams(String[] strs) {
int len = strs.length;
String str;
char[] chArray;
ArrayList<String> temp;
for (int i = 0; i < strs.length; i++) {
str = strs[i];
chArray = str.toCharArray();
Arrays.sort(chArray);
str = new String(chArray);
if (map.containsKey(str)) {
temp = map.get(str);
temp.add(strs[i]);
map.put(str, temp);
} else {
temp = new ArrayList<>();
temp.add(strs[i]);
map.put(str, temp);
}
}
for (ArrayList<String> l : map.values()) {
if (l.size() > 1) {
list.addAll(l);
}
}
return list;
}
}