Java Practice [HashMap]
Group Anagrams https://leetcode.com/problems/group-anagrams/
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
HashMap<String, List<String>> hm = new HashMap<>();
for(int i=0;i<strs.length;i++) {
char[] s = strs[i].toCharArray();
Arrays.sort(s);
String k = new String(s);
if(hm.containsKey(k)) {
hm.get(k).add(strs[i]);
} else {
List<String> ls = new ArrayList<String>();
ls.add(strs[i]);
hm.put(k,ls);
}
}
List<List<String>> ans = new ArrayList<List<String>>();;
for (String p:hm.keySet()) {
ans.add(hm.get(p));
}
return ans;
}
}
Comments
Post a Comment