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

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;
    }
}
posted @ 2018-07-22 17:10 ACBingo 阅读(...) 评论(...) 编辑 收藏