欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

[leetcode] 49. 字母异位词分组

程序员文章站 2022-07-12 12:49:21
...

49. 字母异位词分组

桶排分类即可

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        Map<String, List<String>> map = new HashMap<>();
        for (String str : strs) {
            map.computeIfAbsent(fun(str), k -> new ArrayList<>()).add(str);
        }
        return new ArrayList<>(map.values());
    }

    public String fun(String str) {
        Map<Character, Integer> map = new HashMap<>();
        for (int i = 0; i < str.length(); i++) {
            map.putIfAbsent(str.charAt(i), 0);
            map.put(str.charAt(i), map.get(str.charAt(i)) + 1);
        }
        String key = "";
        char[] chars = new char[map.size()];
        int i = 0;
        for (Character character : map.keySet()) {
            chars[i++] = character;
        }
        Arrays.sort(chars);
        for (char aChar : chars) {
            key += aChar + ":" + map.get(aChar) + ",";
        }
        return key;
    }
}

上一篇: RabbitMQ

下一篇: RabbitMQ