Answer to Question #76523 in C++ for LEE JIA WEI

Question #76523
Write a function num_uniques that takes in a string and returns the number of unique characters in the string.

Hint: You can use a std::map to maintain a count of the characters.

#include <string>

using namespace std;

int num_uniques(string str) {

//code..

}
1
Expert's answer
2018-04-25T08:59:13-0400
#include <map>
#include <string>

using namespace std;

int num_uniques(string str)
{
// Map store information about the count of characters
map<char, int> chars;

const int strLen = str.length();
for (int i = 0; i < strLen; ++i)
{
// Try to insert new element in map with current symbol
const auto insertRes = chars.insert(make_pair(str[i], 1));

/* If result of insert == false, then the symbol
* already exist in the map
* so we just increment its count
*/
if(!insertRes.second)
++(insertRes.first->second);
}

// Count symbols that were repeated only once
int numOfUniques = 0;
for (const auto it : chars)
if(it.second == 1)
++numOfUniques;

return numOfUniques;
}

int main()
{
const string str = "AA BB C D E fF";
const int numOfUniques = num_uniques(str);
printf("Num of unique characters: %d\n", numOfUniques);

system("pause");
return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS