Wednesday, 2 January 2013

ANAGRAM STRINGS


Write a function to check whether two given strings are anagram of each other or not. An anagram of a string is another string that contains same characters, only the order of characters can be different. For example, “abcd” and “dabc” are anagram of each other.


SOLUTION---

This method assumes that the set of possible characters in both strings is small. In the following implementation, it is assumed that the characters are stored using 8 bit and there can be 256 possible characters.
1) Create count arrays of size 256 for both strings. Initialize all values in count arrays as 0.
2) Iterate through every character of both strings and increment the count of character in the corresponding count arrays.
3) Compare count arrays. If both count arrays are same, then return true.


SOURCE CODE--


#include
#include
int main()
{
    int count1[256];//initialize the two count array of size 256
    int count2[256];
    char str1[1000];
    char str2[1000];
    int len1,len2,i;
    //initialize all values of array count1 and count2 equals to zero 
    for(i=0;i<256;i++)
    {
        count1[i]=0;
        count2[i]=0;
    }
    scanf("%s",str1);
    scanf("%s",str2);
    //find length of both the strings//
    len1=strlen(str1);
    len2=strlen(str2);
    //if length of strings are not equal then strings are not anagram
    if(len1!=len2)
        printf("\ngiven strings are not anagram\n");
    else
    {
        for(i=0;i<len1;i++)
        {
            count1[str1[i]]++;
            count2[str2[i]]++;
        }
        //checking the no. of counts of both array count1 and count2
        for(i=0;i<256;i++)
        {
            if(count1[i]!=count2[i])
            {
                printf("\ngiven strings are not anagram\n");
                break;
            }
        }
        /*if all the no. of counts of one string is equal to no. of counts of a another string then loop will not terminate untill i become equal to 256*/  
        if(i==256)
        {
            printf("\ngiven strings are anagram\n");
        }
    }
    return 0;
}
 



time complexity -O(N)

2 comments:

Anonymous said...

but this code wont work for anagrams where t2 strings are :
s1: Vacation time
s2 :I am not active

pls suggest solutions for these types of anagrams.

CHANDAN SINGH said...

use gets instead of scanf in this case :)
it will work !