C#版 - Leetcode49 - 字母异位词分组 - 题解

Leetcode49.Group Anagrams


在线提交:
https://leetcode.com/problems/group-anagrams/

题目描述

给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。

示例:

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

说明:

  • 所有输入均为小写字母。

  • 不考虑答案输出的顺序。

    • Difficulty: Medium

    • Total Accepted: 238 K

    • Total Submissions: 577.1K

    • Contributor: LeetCode

Related Topics:
Hash Table
String

Similar Questions:
Valid Anagram
Group Shifted Strings

思路:

方法1 已AC代码:

public class Solution { public IList<IList<string>> GroupAnagrams(string[] strs) { IList<IList<string>> res = new List<IList<string>>(); if (strs == null || strs.Length == 0) return res; Dictionary<string, int> dict = new Dictionary<string,int>(); foreach (var str in strs) { char[] ch = str.ToCharArray(); Array.Sort(ch); string s = new string(ch); if (dict.ContainsKey(s)) { IList<string> list = res[dict[s]]; list.Add(str); } else { IList<string> list = new List<string>(); list.Add(str); dict.Add(s, res.Count); res.Add(list); } } return res; } } 

Rank:

You are here!
Your runtime beats <kbd>30.94%</kbd> of csharp submissions.

方法2:

 

https://www.youtube.com/watch?v=YQbjqVjOESk