Checking Anagram

0

Here is a simple code to check if given 2 strings are anagram are not

Just sort the 2 strings and compare if both strings are same

#include<iostream>
#include<algorithm>
#include<string.h>
using namespace std;
int main(){

char str1[]=”adamm”;
char str2[]=”madam”;
sort(str1,str1+strlen(str1));
sort(str2,str2+strlen(str2));
if(strcmp(str1,str2)==0)
cout<<“YES”;
else
cout<<“NO”;

}

This is not efficient since you are using sort function twice

An efficient way to check is to create array of 256 characters(includes all ASCII characters)

initialize all array elements as zero and then increment the array element whose index value is the ASCII equivalent of the character encountered in the string

Rest is self explanatory in the given code

#include<iostream>
#include<string.h>
using namespace std;
bool checkAnagrams(char *s,char *t){
int num_unique,num_counted;
num_unique=num_counted=0;
int CharCount[256]={0};
if(strlen(s)!=strlen(t))
return false;
for(int i=0;i<strlen(s);i++){
if(CharCount[s[i]]==0)
num_unique++;
CharCount[s[i]]++;
}
for(int i=0;i<strlen(t);i++){
if(CharCount[t[i]]==0)
return false;
CharCount[t[i]]–;
if(CharCount[t[i]]==0){
num_counted++;

}

}
if(num_counted==num_unique)
return true;
return false;
}
int main(){
char s[]=”helloa”;
char t[]=”oheall”;
if(checkAnagrams(s,t))
cout<<“YES”;
else
cout<<“NO”;
return 0;
}