Thursday, 7 November 2013

[C Programming] Check if two strings are anagrams

Anagram: Two strings S1 and S2 are called anagrams when string S2 can be formed if we rearrange the letters in string S1 and vice-versa.


Example: S1 = god, S2 = dog

Solution:
------------
If we apply XOR property here then we can easily find the given strings are anagrams or not.

1 XOR 1 = 0
1 XOR 0 = 1
a XOR z = 1
s XOR s = 0

If Inputs to the XOR operator are equal then result would be ZERO.

Apply XOR for each alphabet in both strings. If the result is ZERO then the strings are anagrams else not anagrams. It may not be sufficient condition since the strings "aaa" and "bbb" are not anagrams but still the XOR of these two strings is ZERO. Hence, one more check was needed to eliminate these usecases. Compute the sum of ascii value of two strings and check if they are equal. If equal then the two given strings are anagrams.

Sample code (anagram_string.c):
--------------------------------------
  #include<stdio.h>
  #include<string.h>

  void main(int argc, char *argv[])
  {
          char *str1, *str2;
          int xor, i;
          int sum1 = 0, sum2 = 0;


          if ( argc != 3 ) /* argc should be 3 for correct execution */
          {
                  /* argv[0] is the program name */
                  printf( "usage: %s string1 string2\n", argv[0] );
                  return;
          }

          str1 = argv[1];
          str2 = argv[2];

          printf("Entered strings \"%s\" and \"%s\"\n", str1, str2);

          if (strlen(str1) != strlen(str2)) {
                  printf("Given Strings are not anagrams\n");
                  return;
          }

          for (i = 0; i < strlen(str1); i++) {
                  xor ^= str1[i];
                  xor ^= str2[i];
                  sum1 += str1[i];
                  sum2 += str2[i];
          }

          if (!xor && (sum1 == sum2))
                  printf("Given Strings are anagrams\n");
          else
                  printf("Given Strings are not anagrams\n");

  }

Output:
======
gcc anagram_string.c
./a.out ram arm

Entered strings "ram" and "arm"
Given Strings are anagrams

No comments:

Post a Comment

You might also like

Related Posts Plugin for WordPress, Blogger...