LeetCode Online Judge 题目C# 练习 - Anagrams

Given an array of strings, return all groups of strings that are anagrams.

Note: All inputs will be in lower-case.

e.g. "tea","and","ate","eat","dan".   return "and","dan","tea","ate","eat"

anangrams意思是重新排列字母顺序构成一个新词。

 1         public static List<string> Anagrams(string[] S)
 2         {
 3             List<string> ret = new List<string>();
 4             List<string> sortedS = new List<string>();
 5             Dictionary<string, List<int>> map = new Dictionary<string, List<int>>();
 6 
 7             for (int i = 0; i <= S.GetUpperBound(0); i++)
 8             {
 9                 char[] temp = S[i].ToCharArray();
10                 Array.Sort(temp);
11                 sortedS.Add(new string(temp));
12             }
13             for (int i = 0; i <= sortedS.Count - 1; i++)
14             {
15                 if (map.ContainsKey(sortedS[i]))
16                     map[sortedS[i]].Add(i);
17                 else
18                     map.Add(sortedS[i], new List<int> { i });
19             }
20 
21             foreach (var item in map)
22             {
23                 if(item.Value.Count > 1)
24                     foreach (int index in item.Value)
25                     {
26                         ret.Add(S[index]);
27                     }
28             }
29             return ret;
30         }

代码分析:

  这题解题关键是先把所有string先排列,然后放到一个新的List<string> SortedS里面。

  之后就简单了,用一个Dictionary<string, List<int>>, 把在SortedS里面相同的string记录起来他的index。然后再迭代这个map,把Value.Count > 1的回到原来的S[]里面找。

  用Dictionary插入元素的时候要注意一下:

  •   在C++ STL提供的map里,插入的时候直接map[Key] = Value; 就可以了,但是C#里头如果map.ContainKey(Key) == false; 直接map[Key] = Value会抛出异常,我们要使用map.Add(Key, Value);

转载于:https://www.cnblogs.com/etcow/archive/2012/06/29/2568922.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值