可能重复:
What is an easy way to tell if a list of words are anagrams of each other?
在C#中编写函数的最佳方法(性能范围)是什么,它接受两个字符串,当字符串是彼此的字符串时返回true,否则返回false。字谜的例子是:
abet beat beta bate
abides biased
在实现这个时,每个字符串中是否有空格?
任何想法都会非常感激!
答案 0 :(得分:8)
一种简单(天真?)的方式,使用LINQ:
"abides".OrderBy(c=>c).SequenceEqual("biased".OrderBy(c=>c))
答案 1 :(得分:6)
一个简单的解决方案是按字母顺序对字符进行排序并将它们相互比较。
public static class AnagramExtensions
{
public static bool IsAnagramOf(this string word1, string word2)
{
return word1.OrderBy(x => x).SequenceEqual(word2.OrderBy(x => x));
}
}
然后,使用它:
static void Main()
{
string word1 = "cat";
string word2 = "tac";
Console.WriteLine(word1.IsAnagramOf(word2));
string word3 = "cat";
string word4 = "dog";
Console.WriteLine(word3.IsAnagramOf(word4));
}
这种情况下的输出是
True
False
答案 2 :(得分:0)
如何不这样做:从每个字符串中删除所有空格。使用Algorithm to generate anagrams中的一种算法生成第一个字符串的所有可能排列。最后,搜索一个匹配的permeations列表;如果有,那么这两个是字谜,否则,不是。
答案 3 :(得分:0)
我有一个字符串列表(不仅仅是两个字符串)的解决方案。 如果您对此感兴趣,则可以使用它。
给出一个字符串数组,除去作为早先字符串的字谜的每个字符串,然后按存储顺序返回剩余的数组。
private static List<string> GencoAnagrams(List<string> textList)
{
var listCount = textList.Count;
if (listCount == 1) return textList;
for (var j = 1; j < listCount; j++)
{
for (var i = 0; i < j; i++)
{
if (string.Concat(textList[j].OrderBy(x => x)).Equals(string.Concat(textList[i].OrderBy(y => y))))
{
textList.RemoveAt(j);
--listCount;
--j;
if (listCount == 1) break;
}
}
if (listCount == 1) break;
}
return textList;
}