49. 字母异位词分组
题目描述
输入字符串数组 strs。如果一个字符串重新排列字母后能得到另一个,即两者各字母出现次数完全相同,它们就互为字母异位词。
把互为字母异位词的字符串归入同一组,返回所有分组。每个字符串恰好属于一组。组与组之间、组内字符串之间的顺序都不限。
示例 1
输入:strs = ["eat","tea","tan","ate","nat","bat"] 输出:[["eat","tea","ate"],["tan","nat"],["bat"]]
解释:eat、tea、ate 字母相同归为一组,tan、nat 归为一组,bat 单独一组。
示例 2
输入:strs = [""] 输出:[[""]]
解释:只有一个空字符串,自成一组。
示例 3
输入:strs = ["a"] 输出:[["a"]]
数据范围
1 <= strs.length <= 10^40 <= strs[i].length <= 100strs[i]只含小写字母。
解题思路:排序后的字符串作为键
把每个单词排序后的字符元组作为规范键。相同字母频次会得到同一个键,用字典把原词追加到对应列表。
为什么正确
处理完前 i 个单词后,字典每个桶恰好包含这些单词按字母多重集合划分的结果。
复杂度分析
设 n 为单词数、k_i 为第 i 个单词长度、L=Σk_i,时间 O(n+Σ k_i log(k_i+1)),额外空间 O(n+L),包括排序临时列表、元组键和分组列表(原字符串只保存引用)。
易错点
只按字符串长度分组不够;字符频次必须完全一致。
参考代码
Python、Java、C++、Go、JavaScript、TypeScript 六种语言,逻辑一致。
from collections import defaultdict
class Solution:
def groupAnagrams(self, strs):
groups = defaultdict(list)
for s in strs:
groups[tuple(sorted(s))].append(s)
return list(groups.values())class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
Map<String, List<String>> groups = new HashMap<>();
for (String s : strs) {
char[] cs = s.toCharArray(); Arrays.sort(cs);
groups.computeIfAbsent(new String(cs), k -> new ArrayList<>()).add(s);
}
return new ArrayList<>(groups.values());
}
}class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, vector<string>> groups;
for (string& s : strs) {
string key = s; sort(key.begin(), key.end());
groups[key].push_back(s);
}
vector<vector<string>> res;
for (auto& [key, g] : groups) res.push_back(g);
return res;
}
};func groupAnagrams(strs []string) [][]string {
groups := map[string][]string{}
for _, s := range strs {
b := []byte(s); sort.Slice(b, func(i, j int) bool { return b[i] < b[j] })
groups[string(b)] = append(groups[string(b)], s)
}
res := [][]string{}
for _, g := range groups {
res = append(res, g)
}
return res
}var groupAnagrams = function(strs) {
const groups = new Map();
for (const s of strs) {
const key = [...s].sort().join('');
if (!groups.has(key)) groups.set(key, []);
groups.get(key).push(s);
}
return [...groups.values()];
};function groupAnagrams(strs: string[]): string[][] {
const groups = new Map<string, string[]>();
for (const s of strs) {
const key = [...s].sort().join('');
if (!groups.has(key)) groups.set(key, []);
groups.get(key)!.push(s);
}
return [...groups.values()];
};其他解法
两者都用哈希表分组,只是“规范化键”不同:排序键要花 O(k log k),与字符集无关;计数键只需 O(k + 26),但依赖小写字母这一有限字符集。
解法 2:字母计数作为键 时间 O(n·(k + 26)),空间 O(n·(k + 26))
两个字符串互为字母异位词,当且仅当 26 个字母各自的出现次数相同。对每个字符串统计长度为 26 的计数数组,把它转成哈希键(Python 用元组,Go 直接用 [26]int 数组,其他语言用带分隔符的字符串,如 "1#0#2#…"),相同键的字符串放进同一组。
去掉了对每个字符串的排序,字符串越长优势越明显。代价是每个键固定 26 个分量,字符串很短时反而不比排序快;字符集变大(如 Unicode)时计数数组也要随之变大,此时排序键更通用。
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
groups = defaultdict(list)
for s in strs:
cnt = [0] * 26
for ch in s:
cnt[ord(ch) - ord('a')] += 1
groups[tuple(cnt)].append(s)
return list(groups.values())class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
Map<String, List<String>> groups = new HashMap<>();
for (String s : strs) {
int[] cnt = new int[26];
for (char c : s.toCharArray()) cnt[c - 'a']++;
StringBuilder sb = new StringBuilder();
for (int x : cnt) sb.append(x).append('#');
groups.computeIfAbsent(sb.toString(), k -> new ArrayList<>()).add(s);
}
return new ArrayList<>(groups.values());
}
}class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, vector<string>> groups;
for (string& s : strs) {
string key;
int cnt[26] = {0};
for (char c : s) cnt[c - 'a']++;
for (int i = 0; i < 26; i++) key += to_string(cnt[i]) + '#';
groups[key].push_back(s);
}
vector<vector<string>> res;
for (auto& [key, g] : groups) res.push_back(g);
return res;
}
};func groupAnagrams(strs []string) [][]string {
groups := map[[26]int][]string{}
for _, s := range strs {
var cnt [26]int
for _, c := range s {
cnt[c-'a']++
}
groups[cnt] = append(groups[cnt], s)
}
res := make([][]string, 0, len(groups))
for _, g := range groups {
res = append(res, g)
}
return res
}var groupAnagrams = function(strs) {
const groups = new Map();
for (const s of strs) {
const cnt = new Array(26).fill(0);
for (const c of s) cnt[c.charCodeAt(0) - 97]++;
const key = cnt.join('#');
if (!groups.has(key)) groups.set(key, []);
groups.get(key).push(s);
}
return [...groups.values()];
};function groupAnagrams(strs: string[]): string[][] {
const groups = new Map<string, string[]>();
for (const s of strs) {
const cnt: number[] = new Array(26).fill(0);
for (const c of s) cnt[c.charCodeAt(0) - 97]++;
const key = cnt.join('#');
if (!groups.has(key)) groups.set(key, []);
groups.get(key)!.push(s);
}
return [...groups.values()];
}