题目:
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.
题目解释:相同字母组成的字符串分到一类,其中也要求字母个数相同,用HashMap来判别public class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
if(strs==null||strs.length==0) return null;
List<List<String>> result = new ArrayList<List<String>>();
HashMap<String,List<String>> store = new HashMap<String,List<String>>();
for(String s : strs){
char[] mid = s.toCharArray();
Arrays.sort(mid);
String new_s = String.valueOf(mid);
if(store.containsKey(new_s)){
store.get(new_s).add(s);
}else{
List<String> slist = new ArrayList<String>();
slist.add(s);
store.put(new_s, slist);
}
}
Set<String> keyset = store.keySet();
for(String middle : keyset)
result.add(store.get(middle));
return result;
}
}
注意点:
1.char[] 转成String 要用String.valueof()函数来转化,如果直接用toString()转换成地址,与预想结果不同
2.Java中Set是一个不包含重复元素的集合,添加相同元素则直接被替换掉,访问直接for遍历即可