HashMap:字母异位词分组

59 阅读1分钟

leetcode:49. 字母异位词分组

题目描述

给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。

字母异位词 是由重新排列源单词的所有字母得到的一个新单词。

示例

输入: strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
输出: [["bat"],["nat","tan"],["ate","eat","tea"]]

解题思路

异位词分配相同的key,通过Map得到对应的stringGroups

key的设计

  • 字符串中字符+对应频次的形式char + charCnt,比如a1c21d1
  • 排序好的字符串sortedString,比如aabc

代码示例:

class Solution {

    private static final char[] CHARS = new char[26];
    static {
        for (int i = 0; i < 26; i++) {
            CHARS[i] = (char) ('a' + i);
        }
    }

    public List<List<String>> groupAnagrams(String[] strs) {
        Map<String, List<String>> map = new HashMap<>();
        for (String str : strs) {
            String key = getKey(str);
            List<String> list = map.getOrDefault(key, new ArrayList<>());
            list.add(str);
            map.put(key, list);
        }
        return new ArrayList<>(map.values());
    }

    String getKey(String s) {
        StringBuilder sb = new StringBuilder();
        int[] cnt = new int[26];
        for (char c : s.toCharArray()) {
            cnt[c - 'a']++;
        }
        for (int i = 0; i < 26; i++) {
            if (cnt[i] > 0) {
                sb.append(CHARS[i]).append(cnt[i]);
            }
        }
        return sb.toString();
    }
}