LeetCode 面试题 10.02. 变位词组

文章目录

一、题目

编写一种方法,对字符串数组进行排序,将所有变位词组合在一起。变位词是指字母相同,但排列不同的字符串。

注意:本题相对原题稍作修改

示例:

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

\["ate","eat","tea"\], \["nat","tan"\], \["bat"

]

说明:

  • 所有输入均为小写字母。
  • 不考虑答案输出的顺序。

点击此处跳转题目

二、C# 题解

分为三个步骤:

  1. 将同一排列的字符串 s 转换为唯一标识 key;
  2. 使用字典将同一 key 的 s 记录在同一组;
  3. 字典结果转化为列表。
csharp 复制代码
public class Solution {
    public int[]         Record = new int[26];         // 记录字符串 s 每个字符出现的次数
    public StringBuilder Sb     = new StringBuilder(); // 用于将 Record 转化为对应字符串

    public IList<IList<string>> GroupAnagrams(string[] strs) {
        Dictionary<string, IList<string>> dic = new Dictionary<string, IList<string>>();

        foreach (string str in strs) {
            string key = GetKey(str);                    // 获取唯一标识
            if (dic.ContainsKey(key)) dic[key].Add(str); // 判断字典中是否存在
            else dic[key] = new List<string> { str };
        }

        return new List<IList<string>>(dic.Values); // 结果转换
    }

    // 获取字符串 s 对应排列的唯一标识
    public string GetKey(string s) {
        // 清空缓存
        for (var i = 0; i < Record.Length; i++) { Record[i] = 0; }
        Sb.Clear();

        foreach (char t in s) { Record[t - 'a']++; }      // 统计 s 中每个字符出现的次数
        foreach (int t in Record) { Sb.Append('-' + t); } // 转化为对应字符串,添加 '-' 以消除歧义性
        return Sb.ToString();
    }
}
csharp 复制代码
foreach (int t in Record) { Sb.Append('-' + t); } // 转化为对应字符串,添加 '-' 以消除歧义性

这句话中多添加 '-' 是避免后续字符的统计次数影响到当前字符。例如:对于字符 '121' 可以表示为如下两种情况:

  1. '1-21':a 统计了 1 次,b 统计了 21 次;
  2. '12-1':a 统计了 12 次,b 统计了 1 次。

  • 时间:164 ms,击败 100.00% 使用 C# 的用户
  • 内存:64.09 MB,击败 80.00% 使用 C# 的用户
相关推荐
小月球~6 小时前
天梯赛 · 并查集
数据结构·算法
仍然.7 小时前
算法题目---模拟
java·javascript·算法
6Hzlia8 小时前
【Hot 100 刷题计划】 LeetCode 118. 杨辉三角 | C++ 动态规划题解
c++·leetcode·动态规划
潇冉沐晴9 小时前
DP——背包DP
算法·背包dp
GIOTTO情9 小时前
2026 世界互联网大会亚太峰会|AI 时代媒介投放的技术实战与算法优化
人工智能·算法
逆境不可逃9 小时前
LeetCode 热题 100 之 543. 二叉树的直径 102. 二叉树的层序遍历 108. 将有序数组转换为二叉搜索树 98. 验证二叉搜索树
算法·leetcode·职场和发展
计算机安禾9 小时前
【数据结构与算法】第19篇:树与二叉树的基础概念
c语言·开发语言·数据结构·c++·算法·visual studio code·visual studio
副露のmagic10 小时前
哈希章节 leetcode 思路&实现
算法·leetcode·哈希算法
副露のmagic10 小时前
字符串章节 leetcode 思路&实现
windows·python·leetcode
csuzhucong10 小时前
puzzle(1037)黑白、黑白棋局
算法