LeetCode 面试题 10.02. 变位词组

文章目录

  • 一、题目
  • 二、C# 题解

一、题目

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

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

示例:

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

说明:

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

  点击此处跳转题目。

二、C# 题解

  分为三个步骤:

  1. 将同一排列的字符串 s 转换为唯一标识 key;
  2. 使用字典将同一 key 的 s 记录在同一组;
  3. 字典结果转化为列表。
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();
    }
}
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# 的用户

你可能感兴趣的:(LeetCode写题记录,leetcode,算法,职场和发展,c#)