Solution
#include <string>
#include <iostream>
#include <iomanip>
#include <unordered_map>
#include <limits>
#include <algorithm>
using namespace std;
char FindFirstNonrepeatedChar(string& str)
if (str.size() == 0) {
cout << "Input string is empty" << endl;
return -1;
typedef struct {
int first_pos;
int count;
} Info;
unordered_map<char, Info> umap;
int i = 0;
for (auto c : str) {
if (umap.find(c) != umap.end()) {
umap[c].count++;
else {
umap[c] = { i, 1 };
}
}
{
}
i++;
}
}
}
}
};
{
}
}
i = numeric_limits<int>::max();
for (auto ui : umap) {
if (ui.second.count == 1) i = min<int>(i, ui.second.first_pos);
return (i == numeric_limits<int>::max()) ? -1 : str[i];
int main()
string strs[] = {
"Salesforce is the best company to work for",
"",
"world",
"aaa",
"aaabbb",
"hello",
"aaabbbc"
for (auto str : strs) {
cout << "Input string: " << str << endl;
char c = FindFirstNonrepeatedChar(str);
if (c != -1) {
cout << "The first non-repeated character is: " << c << endl;
else {
cout << "Cannot find the character" << endl;
cout << endl;
return 0;
}
Output
Input string: Salesforce is the best company to work for
The first non-repeated character is: S
Input string:
Input string is empty
Cannot find the character
Input string: world
The first non-repeated character is: w
Input string: aaa
Cannot find the character
Input string: aaabbb
Cannot find the character
Input string: hello
The first non-repeated character is: h
Input string: aaabbbc
The first non-repeated character is: c
Press any key to continue . . .
Find a 1st non-repeated char in the string - Jan 30, 2016 5:54:17 AM