链接:https://leetcode.com/problems/group-anagrams/
这个题目思路很清晰,不难发现能够归并在一起的单词之间的联系:具有相同的字母并且字母的数量相同,怎样来把这两个信息都存储起来呢,可以先对字符串进行字母计数,然后将出现次数非0的按照”字母“+”该字母的数量“进行字符拼接,通过HashMap将同类信息-同类的多个字符串的key-value存储起来。
直接上代码;
class Solution {
public static List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> ret=new LinkedList<>();
HashMap<String, LinkedList<String>> hashmap=new HashMap<>();
for(int i=0;i<strs.length;i++)
{
String s=strs[i];
int[] count=new int[26];
for(int j=0;j<s.length();j++)
count[s.charAt(j)-'a'] += 1;
String key="";
for(int j=0;j<count.length;j++)
key += new Integer(j).toString()+new Integer(count[j]).toString();
if(hashmap.containsKey(key))
hashmap.get(key).add(strs[i]);
else
{
LinkedList<String> newList =new LinkedList<>();
newList.add(strs[i]);
hashmap.put(key,newList);
}
}
for(String st:hashmap.keySet())
ret.add(hashmap.get(st));
return ret;
}
}