Letter frequency counter?
iamthwee
Posting Expert
5,950 posts since Aug 2005
Reputation Points: 1,543
Solved Threads: 439
Just do a match on the letters
for example hello has:
1 h
1 e
1 o
2 l
Therefore any word which has the same will be an anagram.
iamthwee
Posting Expert
5,950 posts since Aug 2005
Reputation Points: 1,543
Solved Threads: 439
Hey a better way would be to delete the particular letter in the string after you encounter it.
using the string::erase() function.
In the end you will have to just chek if the string is empty(); and then you have a anagram.
Sky Diploma
Practically a Posting Shark
865 posts since Mar 2008
Reputation Points: 673
Solved Threads: 130
Let the string class do all the work. use stringVariable.find() function.
Here is an example :
bool isAnagram(string& str1, string& str2)
{
//check for length equality
if(str1.length() != str2.length())
return false;
if(!str1)
return false;
//check for string equality
if(str1 == str2) return true;
for(int i = 0; i < str1.length(); i++)
{
//search both ways
if(str1.find(str2[i]) == string::npos)
return false;
if(str2.find(str1[i]) == string::npos)
return false;
}
return true;
}
firstPerson
Senior Poster
3,923 posts since Dec 2008
Reputation Points: 841
Solved Threads: 608
Correction : Its
if(!str1[0])
return false;
and not
if(!str1)
return false;
firstPerson
Senior Poster
3,923 posts since Dec 2008
Reputation Points: 841
Solved Threads: 608
It checks to see if there is a string to check for anagram.
Since technically this check below :
if(str1.length() != str2.length())
return false;
could pass if both string is null;
So it checks to see if they are null;
Also I only need to check 1 string for null, since it will already
be determined that they both have the same length.
firstPerson
Senior Poster
3,923 posts since Dec 2008
Reputation Points: 841
Solved Threads: 608
Well, THis was my approach to the code.
for (int a=0; a<str1.size();a++)
{
size_t val=str2.find(str1[a]);
if(val==string::npos)
return false;
else
str2.erase(val,val);
}
return str2.empty();
THough i dint try it out, hope it works fine.
Sky Diploma
Practically a Posting Shark
865 posts since Mar 2008
Reputation Points: 673
Solved Threads: 130
A Small change would be .....
str2.erase(val,val);
to
str2.erase(val,1);
Thanks to tux4life.
Sky Diploma
Practically a Posting Shark
865 posts since Mar 2008
Reputation Points: 673
Solved Threads: 130
And....Another approach (maybe not the most efficient one):
bool isAnagram(string str1, string str2)
{
sort(str1.begin(), str1.end());
sort(str2.begin(), str2.end());
if(str1 == str2) return true;
return false;
}
(You'll need to include the algorithm header file, you can do this by adding the following include directive to your program: #include <algorithm> )
tux4life
Nearly a Posting Maven
2,350 posts since Feb 2009
Reputation Points: 2,134
Solved Threads: 243
firstPerson
Senior Poster
3,923 posts since Dec 2008
Reputation Points: 841
Solved Threads: 608