Given an array of strings, group anagrams together.
For example, given: [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”],
Return:
[
[“ate”, “eat”,”tea”],
[“nat”,”tan”],
[“bat”]
]
public class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> rst = new ArrayList<List<String>>();
if(strs == null || strs.length == 0) return rst;
HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
for(int i = 0; i < strs.length; i++){
String str = strs[i];
int[] count = new int[26];
for(int j = 0; j < str.length(); j++){
char ch = str.charAt(j);
count[ch-'a']++;
}
String key = Arrays.toString(count);
if(!map.containsKey(key)){
map.put(key, new ArrayList<String>());
}
map.get(key).add(str);
}
for(ArrayList<String> al : map.values()){
rst.add(al);
}
return rst;
}
}