Answers for "count the occurrences ofanagram"

C++
0

count the occurrences ofanagram

//this solution is for when both the string have same type of character
//example: aabaabaa and aaba

#include <bits/stdc++.h>

using namespace std;

int main()
{
    string s,ptr;
    cout<<"Enter the first string:"<<endl;
    cin>>s;
    cout<<"enter the string whose anagram you want to find:"<<endl;
    cin>>ptr;
    int q=s.size();
    int k=ptr.size();
    map<char,int>mp;
    int count=0;
    for(int i=0;i<k;i++)
    {
        if(mp.find(ptr[i])==mp.end())
        {
           mp.insert(make_pair(ptr[i],1));
           count++;
        }
        else
        {
            mp[ptr[i]]++;
        }

    }
    count=mp.size();
    int ans=0;
    int i=0;
    int j=0;
    while(j<q)
    {

        mp[s[j]]--;
        if(mp[s[j]]==0)
        {
            count--;
        }
        if(j-i+1<k)
        {
            j++;
        }
        else if(j-i+1==k)
        {
            if(count==0)
            {
                ans++;
            }
            mp[s[i]]++;
            if(count==0)
            {
                count++;
            }
            i++;
            j++;
        }
    }

    cout<<ans<<endl;
    return 0;
}
Posted by: Guest on June-22-2021

Code answers related to "count the occurrences ofanagram"

Browse Popular Code Answers by Language