(10 marks) Write a functiom in C++ which when passed 2 different lower case
strings s1 and s2 will return true if the strings are anagrams. Note that 2 strings
are anagrams if they contain exactly the same letters with the same frequency.

im doing a past paper for an exam and have come stuck on the very first question :(

bool areAnagrams ( string s1 , string s2 );
{
       if (s1.size() != s2.size())
              return false;

       else
       {
        //compare each letter of a string but am unsure how to do  that?
        }


}

Recommended Answers

All 2 Replies

Well try it... Its quite simple.Your first check is good.If they are not of same length then they can't be anagrams.

ALGORITHM 1:
Fine now if they are then just initiate two loops and match every letter of the first string with every letter of second string and when you find one such character flag them both as checked and move on with your next computations.

At some point of time before the end of first string(that is before you reach '\0' of first string) you come across a mismatch (that you don't get a pair for one of the characters ) then return false straight away.

ALGORITHM 2:

Assuming your string to consist of only one cased of characters (say lower case or upper case) initialize an array say int counter[26] and initialize all values to 0 assume a variable "index_help" which is 65 (for upper cased) and 97(for lower cased).

Traverse through the string1 as:

for i in loop from 0 to string length of str1
count[ string1 - index_help ]++;

After this you'll have exact count of characters in string1.Now through string2 as

for i in loop from 0 to string length of str2
count[ string2 - index_help ]--;

Finally if they are anagrams the count array after the above loops should hold 0's throughout else can return false.

And so on ....... till ALGORITHM n.

Coding is just about creativity.Think and you'll find infinite umber of ways to achieve the same objective.( Even if they apply Brute force strategy as above ;) ) and then spend time improving it.

Sort two strings in ascending order and compare two strings character by character.

commented: Simple and elegant, what more is there to add. +35
commented: *yup* +21
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.