Saturday, 1 February 2014

Check whether two strings are anagrams or not in c++

Here's the code to check if two strings are anagrams to each other or not...But I personally feel this could be more efficient. So please do comment if you find efficient solution. This program works for every test cases.

  1 #include<iostream> 
  2 using namespace std;
  3 bool anagram(char*,char*); 
  4 int main() 
  5 { 
  6     char s1[100],s2[100];
  7     cout<<"Enter string 1: "; 
  8     gets(s1); 
  9     cout<<"Enter string 2: "; 
 10     gets(s2); 
 11     if(anagram(s1,s2)) 
 12     { 
 13         cout<<"The two strings are anagrams! "; 
 14     } 
 15     else 
 16     { 
 17         cout<<"The two strings are not anagrams! "; 
 18     } 
 19     return 0;
 20 } 
 21 bool anagram(char*s,char*t) 
 22 { 
 23     int l1=strlen(s); 
 24     int l2=strlen(t); 
 25     if(l1!=l2) 
 26         return false; 
 27     int count1[256]={0},i,count2[256]={0}; 
 28     for(i=0;s[i]&&t[i];i++) 
 29     { 
 30         count1[s[i]]++; 
 31         count2[t[i]]++; 
 32     } 
 33     for(i=0;i<256;i++) 
 34     { 
 35         if(count1[i]!=count2[i]) 
 36             return false; 
 37     } 
 38     return true; 
 39 } 
 

No comments:

Post a Comment