给定一个字符串列表,返回一组字符串列表,这些字符串将所有字符串组合在一起 [英] Given a list of strings, return a list of lists of strings that groups all anagrams

查看:113
本文介绍了给定一个字符串列表,返回一组字符串列表,这些字符串将所有字符串组合在一起的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:

给定一个字符串列表,返回一组字符串列表,列出所有字谜。



Ex。给出

Question:
Given a list of strings, return a list of lists of strings that groups all anagrams.

Ex. given

{"trees", "bike", "cars", "steer", "arcs"}



return


return

{ {"cars", "arcs"}, {"bike"}, {"trees", "steer"} }



不确定最好的方法是什么?


Not sure what is the best way?

推荐答案

让我们尝试如下

Lets try as below
string[] words = new string[]{"trees", "bike", "cars", "steer", "arcs"};
var anagrams = words.GroupBy(w=>new string(w.OrderBy(c=>c).ToArray())).ToList();


简单方法?

对它们进行排序。

如果创建一个包含原始字符串并按字母顺序排序的类,则可以按顺序字符串对类的集合进行排序。彼此相邻的是相同的字谜。



但这是你的作业,所以我会让你编码!
Easy way?
Sort them.
If you create a class which contains the original string and it sorted into alphabetical order, you can then sort the collection of your class by the ordered strings. The ones next to each other which are identical are anagrams.

But this is your homework, so I'll let you code it!


请参考以下内容:

http://www.blackwasp.co.uk /LinqAnagramCheck.aspx [ ^ ]

http://www.wiktorzychla。 com / 2008/02 / using-linq-to-find-largest-group-of.html [ ^ ]

http://thecsharper.com/?p=64 [ ^ ]

试试!
Please, refer these:
http://www.blackwasp.co.uk/LinqAnagramCheck.aspx[^]
http://www.wiktorzychla.com/2008/02/using-linq-to-find-largest-group-of.html[^]
http://thecsharper.com/?p=64[^]
Try!


这篇关于给定一个字符串列表,返回一组字符串列表,这些字符串将所有字符串组合在一起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆