C program to calculate the count of all anagrams of a string in another string.
Here is the problem statement from
a Microsoft interview for internships, geeks for geeks:
Given a word and a text, return the count of the occurences of anagrams of the word in the text. For eg. word is “for” and the text is “forxxorfxdofr”, anagrams of “for” will be “ofr”, “orf”,”fro”, etc. So the answer would be 3 for this particular example.
Here is an algorithm I used :
You have a text string and a pattern string. You have to find substrings of the text which are also anagrams of the pattern, and return the total count of such substrings.
Extract all substrings from the string with the same length as of the pattern. This step is very trivial, we use the same in
Naive String Matching.
Now, you have the pattern, as well as the substring, and you have to find whether they are anagrams of the same string. To do this, I use two int arrays of 26 size (assuming the strings are all lower case), initialised to zero. Here's the main logic of my algorithm:
Consider each element of the array representative of one alphabet. When I encounter the alphabet in the string, I update the corresponding element in my int array to reflect the count of that alphabet. So, if my string is "abca", then my array will be {2,1,1,0,0,.....}.
How is this method useful? Note that for any anagram of my string, my int array will be the same: let's say my string is "caab", my int array would still be {2,1,1,0,0,...} because the alphabets in all anagrams will appear the same number of times.
#include <iostream>
#include<string.h>
#include<stdio.h>
using namespace std;
int equals(char* A, char* B)
{
int i,len = strlen(A);
int a[26],b[26];
for(i=0;i<26;i++)
{
a[i]=0;
b[i]=0;
}
for(i=0;i<len;i++)
{
a[A[i]-'a']++;
}
for(i=0;i<len;i++)
{
b[B[i]-'a']++;
}
for(i=0;i<26;i++)
{
if(a[i]!=b[i])
return 0;
}
return 1;
}
int check(char* s1, char* s2)
{
int i,j,len1=strlen(s1), len2=strlen(s2), flag=0;
char arr[len2];
for(i=0;i<=len1-len2;i++)
{
for(j=0;j<len2;j++)
{
arr[j]=s1[i+j];
}
if(equals(arr,s2))
flag++;
}
return flag;
}
int main()
{
char text[50]="",pat[50]="";
cout<<"Enter original string: ";
cin>>text;
cout<<"Enter pattern string: ";
cin>>pat;
cout<<"No. of anagrams in text are :"<<check(text,pat);
return 0;
}
There is another efficient code here:
count-of-anagrams-of-a-text-in-a-given-string