Skip to content

传送门:https://leetcode.cn/problems/group-anagrams/?envType=study-plan-v2&envId=top-100-liked

题意就是我们要将字符串中字母组成相同(包括每个字母出现的数量)的字符串进行分组并输出。

Solution1

我们可以将每个字符串进行排序,这样相同的字符串就一定是一组的,将排序后的字符串作为hash表的键再进行统计,时间复杂度为O(nklogk)

Solution2

我们可以对每个单词进行预处理,统计他每个字母的个数进行拼接成字符串来作为hash表的键,最后再进行统计,时间复杂度为O(nk)

参考代码:

java
class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        List<List<String>> ans = new ArrayList<>();
        Map<String, List<String>> map = new HashMap<>();
        for(String str : strs) {
            int[] str_tot = new int[26];
            for(int i = 0;i < str.length();i++) {
                str_tot[str.charAt(i) - 'a']++; //统计每个字符出现的次数
            }
            StringBuffer tot = new StringBuffer(); //用StringBuffer进行拼接
            for(int i = 0;i < 26;i++) {
                if(str_tot[i] != 0) {
                    tot.append('a' + i);
                    tot.append(str_tot[i]);
                }
            }
            String key = tot.toString();
            List<String> nowKey = map.getOrDefault(key, new ArrayList<String>()); //获取map原本里面的值,如果为空则创建空的ArrayList
            nowKey.add(str); //将新的字符串添加进去
            map.put(key, nowKey);
        }
        for(Map.Entry<String, List<String>> kv: map.entrySet()) {
            ans.add(kv.getValue()); //统计答案
        }
        return ans;
    }
}