C++ Checking For Anagrams using a MAP. bool isAnagram(string str1, string str2);
ID: 3776787 • Letter: C
Question
C++ Checking For Anagrams using a MAP.
bool isAnagram(string str1, string str2);
Use the STL map to test whether or not two strings are anagrams of each other. Recall that anagrams are defined as two words that contain all of the same letters. Here are some examples: car & arc are anagrams scab & cabs are anagrams scamper & campers are anagrams car & car are anagrams scars & crass are anagrams cat & ca are NOT anagrams cats & catz are NOT anagrams cats & catss are NOT anagramsExplanation / Answer
bool isAnagram(string str1, string str2)
{
// Compare string lengths
if ( str1.length() != str2.length() )
return false;
// Instantiate a count map
unordered_map<char, size_t> m;
// Loop over the characters of string str1 incrementing the count for each character and str2 decrementing the count for each character
for ( auto & c : str1 )
++m[toupper(c)];
for ( auto & c : str2 )
--m[toupper(c)];
// Check to see if the mapped values are all zeros
for ( auto & c : str2 )
if ( m[toupper(c)] != 0 )
return false;
return true;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.