problem no 30:(string problem):Anagram.
QUESTION:
Anagram
Given two strings a and b consisting of lowercase characters. The task is to check whether two given strings are an anagram of each other or not. An anagram of a string is another string that contains the same characters, only the order of characters can be different. For example, “act” and “tac” are an anagram of each other.
Example 1:
Input:
a = geeksforgeeks, b = forgeeksgeeks
Output: YES
Explanation: Both the string have same
characters with same frequency. So,
both are anagrams.
Example 2:
Input:
a = allergy, b = allergic
Output: NO
Explanation:Characters in both the strings
are not same, so they are not anagrams.
ANSWER:
bool isAnagram(string a, string b){
int array[128];
for(int i=0;i<128;i++)
{
array[i]=0;
}
for(int i=0;i<a.size();i++)
{
array[(int)a[i]]=array[(int)a[i]]+1;
}
for(int i=0;i<b.size();i++)
{
array[(int)b[i]]=array[(int)b[i]]-1;
}
int flagforzeroarray=1;
for(int i=0;i<128;i++)
{
if(array[i]!=0)
{
flagforzeroarray=0;
}
}
if(flagforzeroarray==0)
{
return false;
}
else
{
return true;
}
}
Comments
Post a Comment