Check whether two strings are anagrams c++ -


#include<iostream.h>  #include<string.h> #include<stdio.h> int main() { char str1[100],str2[100]; gets(str1); gets(str2); int i,j; int n1=strlen(str1); int n2=strlen(str2); int c=0; if(n1!=n2) {           cout<<"\nthey not anagrams ! ";           return 0; } else  {      for(i=0;i<n1;i++)              for(j=0;j<n2;j++)              if(str1[i]==str2[j])              ++c; } if(c==n1) cout<<"yes ! anagram !! "; else  cout<<"no ! "; system("pause"); return 0; 

}

the above program came checking whether 2 strings anagrams . working fine small string larger strings ( tried : listened , enlisted ) giving me 'no !'help !

i lazy, use standard library functionality sort both strings , compare them:

#include <string> #include <algorithm>  bool is_anagram(std::string s1, std::string s2) {   std::sort(s1.begin(), s1.end());   std::sort(s2.begin(), s2.end());   return s1 == s2; } 

a small optimization check sizes of strings same before sorting.

but if algorithm proved bottle-neck, temporarily shed of laziness , compare against simple counting solution:

  1. compare string lengths
  2. instantiate count map, std::unordered_map<char, unsigned int> m
  3. loop on s1, incrementing count each char.
  4. loop on s2, decrementing count each char, check count 0

Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -