is_permutation() in C++ and its application for anagram search
Last Updated :
14 Sep, 2023
is_permutations() is used to check if two containers like string and vector are permutation of each other. It accepts three parameters, the first two parameters are begin and end positions of first object and third parameter begin position of second object.
CPP
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector< int > v1{1, 2, 3, 4};
vector< int > v2{2, 3, 1, 4};
if (is_permutation(v1.begin(), v1.end(), v2.begin()))
cout << "True\n" ;
else
cout << "False\n" ;
vector< int > v3{5, 3, 1, 4};
if (is_permutation(v1.begin(), v1.end(), v3.begin()))
cout << "True\n" ;
else
cout << "False\n" ;
return 0;
}
|
Output :
True
False
Application :
Given a pattern and a text, find all occurrences of pattern and its anagrams in text.
Examples:
Input : text ="forxxorfxdofr"
pat = "for"
Output : 3
There are three anagrams of "for"
int text.
Input : word = "aabaabaa"
text = "aaba"
Output : 4
We have discussed a (n) solution her. But in this post it is done using is_permutation(). Although the complexity is higher than previously discussed method, but the purpose is to explain application of is_permutation().
Let size of pattern to be searched be pat_len. The idea is to traverse given text and for every window of size pat_len, check if it is a permutation of given pattern or not.
CPP
#include<bits/stdc++.h>
using namespace std;
int countAnagrams(string text, string pat)
{
int t_len = text.length();
int p_len = pat.length();
int count = 0;
for ( int i=0; i<=t_len-p_len; i++)
if (is_permutation(text.begin()+i,
text.begin()+i+p_len,
pat.begin()))
count++;
return count;
}
int main()
{
string str = "forxxorfxdofr" ;
string pat = "for" ;
cout << countAnagrams(str, pat) << endl;
return 0;
}
|
Output:
3
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...