leetcode學習筆記39
阿新 • • 發佈:2019-01-09
49. Group Anagrams
Input: [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”],
Output:
[
[“ate”,“eat”,“tea”],
[“nat”,“tan”],
[“bat”]
]
這道題主要用到了HashMap的例子
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
HashMap<String,List<String>> hm = new HashMap <String,List<String>>();
List<List<String>> res=new ArrayList<List<String>>();
for (String str:strs) {
char[] ch=str.toCharArray();
Arrays.sort(ch);
String sorted=new String(ch);
if(hm.containsKey(sorted)){
hm.get(sorted).add(str);
}else {
List< String> list=new ArrayList<String>();
list.add(str);
hm.put(sorted, list);
}
}
res.addAll(hm.values());
return res;
}
}