LeetCode:49
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.
这是LeetCode的第49题,有一个巧妙的解题思路是,利用hash,字母相同的字符串让其hash相同。
public List<List<String>> groupAnagrams(String[] strs) {
if(strs == null || strs.length == 0) return new ArrayList<>();
Map<String, List<String>> map = new HashMap<>();
for(String s : strs){
String k = hash(s);
map.computeIfAbsent(k, s1 -> new ArrayList<>()).add(s);
// List<String> value = map.get(k);
// if(value == null) map.put(k, new ArrayList<>());
// value.add(s);
}
return new ArrayList<>(map.values());
}
private String hash(String s){
int