Friday, 25 September 2015

Anagram using Map STL in C++

#include <string>
#include <iostream>
#include <map>
using namespace std;
int main()
{
  map<char,int> ana;
    map<char,int> ana1;
string s,s1;
int i,f=0;
cin>>s>>s1;

  for(i=0;i<s.length();i++)
  {
  ana[s[i]]++; //indexing each character of input string using map1
  }
 
  for(i=0;i<s1.length();i++)
  {
  ana1[s1[i]]++;   //indexing each character of input string using map2
  }
 
map<char,int>::iterator ii;  //iterator to access each element of map
map<char,int>::iterator jj;
if(ana.size()==ana1.size())
{
    for(ii =ana.begin(),jj=ana1.begin(); ii!=ana.end(); ++ii,++jj)
    {
      if(ii->first==jj->first&&ii->second==jj->second)
      {
      f=1;
      }
      else
      {
      f=0;
      break;
    }
    }

    if(f==0)
    cout<<"NOT";
    else
    cout<<"YEs";
}
else
cout<<"NOT";
return 0;
}

No comments:

Post a Comment