Monday, October 31, 2005

Anagram Checker

/* Program to check whether one string is a permutation of another.
   Google sample problem, Cochin October 2005. */
/* Author: Rohit Krishna Kumar */
/* Home page: http://www.geocities.com/rohitkkumar */

#include 
#include 
#define SIZE 10
int main() {
  char str1[SIZE],str2[SIZE];
  int len1,len2;
  int i,j,k;
  int flag=0;
  printf("Enter the first string: ");
  scanf("%s",str1);
  printf("Enter the second string: ");
  scanf("%s",str2);
  len1=strlen(str1);
  len2=strlen(str2);
  if(len1!=len2) {  /* Obviously */
    printf("Strings are not permutations of each other.\n");
    return 0;
  }
  /* This loop checks if each character in one string 
     is present in the other string. As soon as it finds 
     one character it deletes it from both the strings and
     continues. */
  for(i=0;i<len1;i++) {
    flag=0;
    for(j=0;j<len2;j++) {
      if(str1[i]==str2[j]) {
 for(k=i;k<len1;k++) /* Delete the character from str1 */
   str1[k]=str1[k+1];
 for(k=j;k<len2;k++) /* Delete the character from str2 */
   str2[k]=str2[k+1];
 len1--;   /* Decrease the length of both strings. */
 len2--;
 flag=1;
 i=0;
 j=0;
 break;
      }
    }
    if(!flag) {   /* One character in one string is not there
       in the other */
      printf("Strings are not permutations of each other.\n");
      return 1;
    }
  }
  printf("Strings are permutations of each other.\n");
}

No comments: