Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can check anagram strings in C#

Tags:

string

c#

Given two strings A and B, check if they are anagrams.

Two strings are said to be anagrams, if one string can be obtained by rearranging the letters of another.

Examples of anagrams are

  • dog, god
  • abac, baac
  • 123, 312

abab, aaba and dab, baad are not anagrams.

INPUT :

First line of the input is the number of test cases T. It is followed by T lines, each line has two space separated strings A and B;

OUTPUT

For each test case, print "YES" if they are anagrams, otherwise print "NO". (without quotes)

Constraints

  1. 1 <= T <= 10
  2. A and B both contain only lower case latin letters 'a' to 'z' and digits 0 to 9.
  3. Length of each string A and B does not exceed 5*10^5 (500000)

`

Sample Input            Sample Output
------------------------------------
3                           YES
abcd bcda                   NO
bad daa                     YES
a1b2c3 abc123               NO

How can we do this ?

bool anagramChecker(string first, string second)
{
    if(first.Length != second.Length)
        return false;

    if(first == second)
        return true;//or false: Don't know whether a string counts as an anagram of itself

    Dictionary<char, int> pool = new Dictionary<char, int>();
    foreach(char element in first.ToCharArray()) //fill the dictionary with that available chars and count them up
    {
        if(pool.ContainsKey(element))
            pool[element]++;
        else
            pool.Add(element, 1);
    }
    foreach(char element in second.ToCharArray()) //take them out again
    {
        if(!pool.ContainsKey(element)) //if a char isn't there at all; we're out
            return false;
        if(--pool[element] == 0) //if a count is less than zero after decrement; we're out
            pool.Remove(element);
    }
    return pool.Count == 0;
}
like image 426
smartechno Avatar asked Sep 25 '15 08:09

smartechno


People also ask

What is anagram in C?

Anagram strings are nothing but, all the characters that occur for the same number of times in another string, which we call as anagrams. A user enters two strings. We need to count how many times each letter ('a' to 'z') appears in them and then, compare their corresponding counts.

How do you check if a word is an anagram?

Two words are anagrams of each other if they contain the same number of characters and the same characters. You should only need to sort the characters in lexicographic order, and determine if all the characters in one string are equal to and in the same order as all of the characters in the other string.

What is anagram string?

An anagram of a string is another string that contains the same characters, only the order of characters can be different. For example, “abcd” and “dabc” are an anagram of each other.

How do I check if two strings have the same characters?

In order to compare two strings, we can use String's strcmp() function. The strcmp() function is a C library function used to compare two strings in a lexicographical manner. The function returns 0 if both the strings are equal or the same. The input string has to be a char array of C-style string.


3 Answers

Is this your solution?

string a = "abcd";
string b = "bcda"; // bad daa a1b2c3 abc123

string aa = String.Concat(a.OrderBy(c => c));
string bb = String.Concat(b.OrderBy(c => c));

if (aa == bb)
{
     Console.WriteLine("YES");
}
else
{
     Console.WriteLine("NO");
}

or shorter

if (String.Concat(a.OrderBy(c => c)).Equals(String.Concat(b.OrderBy(c => c))) ...
like image 113
Thomas Krojer Avatar answered Oct 21 '22 23:10

Thomas Krojer


There's the fast way and the simple way:

void Test()
{
    string a = "abccabccabccabccabccabccabccabccabccabccabccabccabccabccabccabcc";
    string b = "bcacbcacbcacbcacbcacbcacbcacbcacbcacbcacbcacbcacbcacbcacbcacbcac";

    IsAnagramSimple(a, b);
    IsAnagramFast(a, b);
}


private bool IsAnagramSimple(string a, string b)
{
    return a.OrderBy(c => c).SequenceEqual(b.OrderBy(c => c));
}

private bool IsAnagramFast(string a, string b)
{
    if (a.Length != b.Length)
    {
        return false;
    }

    var aFrequency = CalculateFrequency(a);
    var bFrequency = CalculateFrequency(b);

    foreach (var key in aFrequency.Keys)
    {
        if (!bFrequency.ContainsKey(key)) return false;
        if (aFrequency[key] != bFrequency[key]) return false;
    }

    return true;
}

private Dictionary<char, int> CalculateFrequency(string input)
{
    var frequency = new Dictionary<char, int>();
    foreach (var c in input)
    {
        if (!frequency.ContainsKey(c))
        {
            frequency.Add(c, 0);
        }
        ++frequency[c];
    }
    return frequency;
}
like image 9
Kvam Avatar answered Oct 22 '22 00:10

Kvam


public bool IsAnagram(string s1,string s2)
{
  if (s1.Length != s2.Length)
     return false;
  var s1Array = s1.ToLower().ToCharArray();
  var s2Array = s2.ToLower().ToCharArray();

  Array.Sort(s1Array);
  Array.Sort(s2Array);

  s1 = new string(s1Array);
  s2 = new string(s2Array);

  return s1 == s2;
}
like image 7
Gokul Avatar answered Oct 21 '22 23:10

Gokul