Sunday, 23 April 2017

Program to check if two strings are anagram or not using STL

Two strings are said to be anagram is one string can be formed by rearranging the characters of the second string and vice versa. C++ Program is given below to check is two strings are anagram are not. In this program we used unordered_map to store the number of appearances of every character in string.

Ex:   string 1: palm
         string 2: malp
         Both strings are anagram

Ex:   string 1:  swap
         string 2:  pass
         Both strings are not anagram

Algorithm:-


1.  Compare the length of both strings. if length of the both string is not equal then return false, else go
      to step 2.
2.  Store the number of appearances of each characters of both strings in two different unordered_map
     or array.
3.  Take any one string, and check that the occurrences of each character of taken string is equal to the
     number of occurrences of the same character in string 2. If occurrences of the character are not
     equal then return false, otherwise repeat step 3 till the end of the string 1 and return true.


Program:

#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;

int main()
{
   std::unordered_map <char,int> m1,m2;
   std::string s1,s2;
   cout<<"\nEnter the string 1: \n";
   cin>>s1;
   cout<<"\n\nEnter the string 2: \n";
   cin>>s2;
   int flag=0;
   if(s1.length()!=s2.length())
   {
         cout<<"\n\nStrings are not anagram\n";
   }
   else
   {
         for(int i=0;i<s1.length();i++)
         {
             m1[s1[i]]++;
             m2[s2[i]]++;
         }
         for(int i=0;i<s1.length();i++)
         {
                if(m1[s1[i]]!=m2[s1[i]])
                {
                      flag=1;
                      break;
                }
         }
         if(flag==1)
         {
                 cout<<"\n\nStrings are not anagram\n";
         }
         else
         {
              cout<<"\n\nStrings are anagram\n";
         }
   }
      return 0;

}


OUTPUT:


 More Programs on Strings


EmoticonEmoticon