Given an array of strings, group anagrams together.
For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"],
Return:
[ ["ate", "eat","tea"], ["nat","tan"], ["bat"] ]
Note: All inputs will be in lower-case.
这道题刚好前几天面试过,把sort的string作为key存在hashmap,能解决所有的anagram的问题
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
HashMap<String,Integer> map = new HashMap<String,Integer>();
ArrayList<List<String>> res = new ArrayList<List<String>>();
int order = 0;
for(int i=0;i<strs.length;i++){
char[] ca = strs[i].toCharArray();
Arrays.sort(ca);
String keyStr = String.valueOf(ca);
if(map.containsKey(keyStr)){
res.get(map.get(keyStr)).add(strs[i]);
}
else{
map.put(keyStr,order);
ArrayList<String> tm = new ArrayList();
tm.add(strs[i]);
res.add(tm);
order++;
}
}
return res;
}
}
本站原创文章皆遵循“署名-非商业性使用-相同方式共享 3.0 (CC BY-NC-SA 3.0)”。转载请保留以下标注:
原文来源:《49. Group Anagrams》