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 List<List<String>> groupAnagrams(String[] strs) {
Map<String,List<String>> map = new HashMap<>();
for (String string:strs){
char[] chars = string.toCharArray();
Arrays.sort(chars);
String value = String.valueOf(chars);
if (!map.containsKey(value)){
List<String> list = new ArrayList<>();
map.put(value,list);
}
map.get(value).add(string);
}
List<List<String>> lists = new ArrayList<>();
for (List<String> list:map.values()) {
lists.add(list);
}
return lists;
}