Given an array of strings, group anagrams together.
For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"]
,
Return:
[ ["ate", "eat","tea"], ["nat","tan"], ["bat"] ]
Note:
- For the return value, each inner list's elements must follow the lexicographic order.
- All inputs will be in lower-case.
public List<List<String>> groupAnagrams(String[] strs) {
int n = strs.length;
List<List<String>> res = new ArrayList<List<String>>();
if (n <= 0)
return res;
HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
ArrayList<String> temp = null;
String str = null;
for (int i = 0; i < n; i++) {
char[] key = strs[i].toCharArray();
Arrays.sort(key);
str = new String(key);
if (map.containsKey(str)) {
temp = map.get(str);
temp.add(strs[i]);
} else {
temp = new ArrayList<String>();
temp.add(strs[i]);
map.put(str, temp);
}
}
Collection<ArrayList<String>> values = map.values();
for (ArrayList<String> r : values) {
Collections.sort(r);
if (r.size() >= 1)
res.add(r);
}
return res;
}