구현

2011-08-16 7 views
5

가능한 중복 :
What is an easy way to tell if a list of words are anagrams of each other?구현

무엇이 가장 좋은 방법 (전체 성능) 두 문자열을 받아 true를 반환 C#에서 함수를 작성하는이다 문자열이 서로의 아나그램이면 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- 각각의 단어가 anagrams-of-each-other라고 말하면서 반 페이지를 차지합니다. :) – shelleybutterfly

0

방법 : 각 문자열에서 공백을 모두 제거하십시오. Algorithm to generate anagrams에서 알고리즘 중 하나를 사용하여 첫 번째 문자열의 모든 가능한 순열을 생성하십시오. 마지막으로 일치 항목에 대한 permuations 목록을 검색하십시오. 만약 하나가 있다면, 그 둘은 아나그램이고, 그렇지 않으면 그렇지 않습니다.