387 First Unique Character in a String
s = "leetcode"
return 0.
s = "loveleetcode",
return 2.int firstUniqChar(string s)
{
// char -> position, frequency
unordered_map<char, pair<int, int>> freq_map;
freq_map.reserve(s.length());
for (int i = 0; i < s.length(); i++) {
if (freq_map.find(s[i]) != freq_map.end()) {
freq_map[s[i]].second++;
}
else freq_map.insert({ s[i], {i, 1} });
}
int index = INT_MAX;
for (auto i : freq_map) {
if (i.second.first < index && i.second.second == 1) {
index = i.second.first;
}
}
return index == INT_MAX ? -1 : index;
}
int main()
{
cout << firstUniqChar("leetcode") << endl;
cout << firstUniqChar("loveleetcode") << endl;
cout << firstUniqChar("ddaann") << endl;
}Last updated