Leetcode热题100--新手出发2
题目
49. 字母异位词分组
给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。
字母异位词 是由重新排列源单词的所有字母得到的一个新单词。
示例 1:
输入: strs = [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”]
输出: [[“bat”],[“nat”,“tan”],[“ate”,“eat”,“tea”]]
示例 2:
输入: strs = [“”]
输出: [[“”]]
示例 3:
输入: strs = [“a”]
输出: [[“a”]]
提示:
1 <= strs.length <= 104
0 <= strs[i].length <= 100
strs[i] 仅包含小写字母
具体实现
排序法
思路及算法:
思路:
将排序后的结果作为字典的键,字典的值为存储相同结果的列表。
实现:
1、遍历当前数组,取得当前值并将其转换为char[] 并将其排序
2、将得到的排序后的结果保存为键:若存在该键,则将该键的列表中添加该参数;若不存在该键,则以排序后的结果为键,创建该参数
string[] str = new string[] { "eat", "tea", "tan", "ate", "nat", "bat" };
public IList<IList<string>> GroupAnagrams(string[] strs)
{
Dictionary<string, IList<string>> result = new Dictionary<string, IList<string>>();
for (int i = 0; i < strs.Length; i++)
{
char[] chars = strs[i].ToCharArray();
Array.Sort(chars);
string key = new string(chars);
if(!result.ContainsKey(key))
{
result.Add(key, new List<string>());
}
result[key].Add(strs[i]);
}
IList<IList<string>> listResult = new List<IList<string>>();
listResult = result.Values.ToList();
return listResult;
}
计数法
思路及算法:
思路:
创建一个可以存储26字母数据的数组,通过char字符串的差值取得每个字符的个数,再进行对比。
实现:
1、遍历当前数组,将取得的当前值进行遍历,通过char字符串的差值取得每个字符的个数
2、遍历刚才取得的差值数组,将每个字符和其个数按照格式转换成字符串
3、将得到的排序后的结果保存为键:若存在该键,则将该键的列表中添加该参数;若不存在该键,则以排序后的结果为键,创建该参数
public IList<IList<string>> GroupAnagrams2(string[] strs)
{
if(strs.Length==0) return new List<IList<string>>();
Dictionary<string, IList<string>> result = new Dictionary<string, IList<string>>();
for (int i = 0; i < strs.Length; i++)
{
int[] counts = new int[26];
for (int j = 0; j < strs[i].Length; j++)
{
int temp = strs[i][j] - 'a';
Debug.Log("temp:" + temp);
counts[temp]++;
}
// 对已经整理好的 字母个数数组 使用string的格式进行包装(字母+个数)
StringBuilder sb= new StringBuilder();
for (int h = 0; h < 26; h++)
{
if (counts[h]!= 0)
{
sb.Append((char)('a' + h));//字母
sb.Append(counts[h]);//个数
}
}
// 在列表里进行数值判断
string key = sb.ToString();
Debug.Log("key:" + key);
if (!result.ContainsKey(key))
{
result.Add(key, new List<string>());
}
result[key].Add(strs[i]);
}
return result.Values.ToList();
}
PS:整体的思路大概如此,按照自己的思路进行整理的,若有问题和可以优化的细节,望各位大佬指点。