public class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
if(strs==null || strs.length == 0){
return new ArrayList<List<String>>();
}
// create a hashmap that saves letters and corresponding anagrams
HashMap<String, List<String>> hm = new HashMap<String, List<String>>();
for (String s : strs) {
// sort s and set it as key
char[] tmp = s.toCharArray();
Arrays.sort(tmp);
String tmp_str = String.valueOf(tmp);
// if the map doesn't contain tmp_str, creat an record
if (!hm.containsKey(tmp_str))
hm.put(tmp_str, new ArrayList<String>());
// put values into the map
hm.get(tmp_str).add(s);
}
return new ArrayList<>(hm.values());
}
}
Leetcode 49. Group Anagrams
最新推荐文章于 2022-08-04 00:22:08 发布