- set a HashMap.
- The key is string with letters in lexicographic order.
- The value is index of list containing anagrams in an ArrayList.
Implementation
public class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
Arrays.sort(strs);
List<List<String>> result = new ArrayList<List<String>>();
HashMap<String, Integer> map = new HashMap<String, Integer>();
for (int i = 0; i < strs.length; i++) {
char[] e = strs[i].toCharArray();
Arrays.sort(e);
String element = String.valueOf(e);
if (map.containsKey(element)) {
result.get(map.get(element)).add(strs[i]);
}
else {
ArrayList<String> list = new ArrayList<String>();
list.add(strs[i]);
result.add(list);
map.put(element, result.size() - 1);
}
}
return result;
}
}