2011-08-16 21 views
5

可能重複:
What is an easy way to tell if a list of words are anagrams of each other?在C#實現字謎功能

什麼是最好的方式(性能寬)寫在C#中,它有兩個字符串並返回true的功能當字符串是彼此的anagrams,否則返回false。字謎的例子有:

abet beat beta bate 
abides biased 

anagrams link

在執行本,是有可能存在於每個字符串空間?

任何想法將非常感激!

+0

作業?如果是這樣,請標記爲這樣。 – Yuck

+0

是否有幫助:http://stackoverflow.com/questions/522112/what-is-an-easy-way-to-tell-if-a-list-of-words-are-anagrams-of-each-other – shelleybutterfly

回答

5

一個簡單的解決方案是按字母順序對字符進行排序並將它們相互比較。

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

8

一個簡單的(幼稚?)的方式,使用LINQ:

"abides".OrderBy(c=>c).SequenceEqual("biased".OrderBy(c=>c)) 
+0

+1非常簡潔,在一行中說什麼一些解決方案在http://stackoverflow.com/questions/522112/what-is-an-easy-way-to-tell-if-a-list-of-每個其他的字都是半個頁面。 :) – shelleybutterfly

0

如何不這樣做:刪除每個字符串的所有空格。使用Algorithm to generate anagrams的算法之一來生成第一個字符串的所有可能的排列。最後,搜索一個匹配的permuations列表;如果有一個,那麼這兩個是anagrams,否則,不是。