The problem is that this code works well for input string of size 4 but for size more than 4 it gives segmentation fault.
The problem is to check the index of all anagrams of a string in another string.
for example: for string1 input abab
and string2 input ab
- it works good but for BACDGABCDA
and ABCD
gives segmentation fault.
#include<bits/stdc++.h>
using namespace std;
void anagram(string s, string p) {
int k = p.length();
string temp = "";
vector<int> v;
int j = 0;
for(int i = 0;i<p.length();i++) {
temp += s[i];
}
sort(temp.begin(), temp.end());
for(int i = p.length();i<s.length();i++) {
if(temp == p && i == p.length()) {
v.push_back(i-k+1);
continue;
}
temp.erase(temp.begin()+(i-k));
temp += s[i];
sort(temp.begin(), temp.end());
if(temp == p) {
v.push_back(i-k+1);
}
}
for (auto& it : v) {
cout << it << ' ';
}
}
int main() {
// This is to find the starting index of all anagrams in a string.
string s = "BACDGABCDA";
string p = "ABCD";
anagram(s, p);
return 0;
}