/*
将上面的两步循环,合成一步,边找变价
*/
public List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> res = new ArrayList<>();
HashMap<HashMap<Character,Integer>, List<String>> lookup = new HashMap<>();
for(int i = 0; i < strs.length; i++)
{
HashMap<Character, Integer> map = scanWord(strs[i]);
if(!lookup.containsKey(map))
lookup.put(map, new ArrayList<>());
lookup.get(map).add(strs[i]);
}
for(List<String> ls : lookup.values())
res.add(ls);
return res;
}
public HashMap<Character, Integer> scanWord(String s)
{
HashMap<Character, Integer> map = new HashMap<>();
for(int i = 0; i < s.length(); i++)
map.put(s.charAt(i), map.getOrDefault(s.charAt(i), 0) + 1);
return map;
}
评论