C# 一个字谜函数在C语言中的实现#
可能重复:C# 一个字谜函数在C语言中的实现#,c#,C#,可能重复: 在C#中编写函数的最佳方式(性能范围)是什么?该函数接受两个字符串,当字符串是彼此的anagram时返回true,否则返回false。字谜的例子有: abet beat beta bate abides biased 在实现这一点时,每个字符串中是否可能有空格 任何想法都将不胜感激 一个简单的解决方案是按字母顺序对字符进行排序,并相互比较 public static class AnagramExtensions { public static bool IsAnagr
在C#中编写函数的最佳方式(性能范围)是什么?该函数接受两个字符串,当字符串是彼此的anagram时返回true,否则返回false。字谜的例子有:
abet beat beta bate
abides biased
在实现这一点时,每个字符串中是否可能有空格
任何想法都将不胜感激 一个简单的解决方案是按字母顺序对字符进行排序,并相互比较
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
使用LINQ的简单(天真)方法:
"abides".OrderBy(c=>c).SequenceEqual("biased".OrderBy(c=>c))
如何不这样做:删除每个字符串中的所有空白。使用处的算法之一生成第一个字符串的所有可能排列。最后,搜索匹配的置换列表;如果有一个,那么这两个是字谜,否则不是 我有一个字符串列表的解决方案(不仅仅是两个字符串)。 如果你对它或其他任何一个感兴趣,你可以使用它 给定一个字符串数组,删除前一个字符串的字谜,然后按存储顺序返回剩余的数组
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;
}
专用静态列表GencoAnagrams(列表文本列表)
{
var listCount=textList.Count;
如果(listCount==1)返回textList;
对于(var j=1;jx)).Equals(string.Concat(textList[i].OrderBy(y=>y)))
{
textList.RemoveAt(j);
--列表计数;
--j;
如果(listCount==1)中断;
}
}
如果(listCount==1)中断;
}
返回文本列表;
}
家庭作业?如果是这样,请将其标记为这样。这是否有帮助:+1的可能副本非常简洁,在一行中说明了某些解决方案需要半页才能说明的内容。:)