Explanation
Algorithm: find the same letter string Group Anagrams
Address: https://leetcode.com/problems/group-anagrams/
Given an array of strings, group anagrams together.
Example:
Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
Note:
All inputs will be in lowercase.
The order of your output does not matter.
Solution
In order to investigate the actual usage HashMap, the sorted string as the key, the same character string in the same list of letters to value.
private String sort(String input) {
char[] chars = input.toCharArray();
Arrays.sort(chars);
return new String(chars);
}
public List<List<String>> groupAnagrams(String[] strs) {
// edge check
if (strs == null || strs.length == 0) {
return null;
}
Map<String, List<String>> map = new HashMap<>();
// build map
for (String s: strs) {
String sortItem = sort(s);
if (!map.containsKey(sortItem)) {
map.put(sortItem, new ArrayList<String>());
}
map.get(sortItem).add(s);
}
return new ArrayList<>(map.values());
}