码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2018-07-22 17:41:04      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:fun   []   rip   des   com   ++   script   public   .com   

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;
    }
}

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

标签:fun   []   rip   des   com   ++   script   public   .com   

原文地址:https://www.cnblogs.com/acbingo/p/9350748.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!