题目
在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).
思路
不能遍历map和unorder_map。map是有序的,只不过这种有序是key的字符串排序,unorder_map是无序的(即不按照字符串进行排序)
#include <iostream>
#include<vector>
#include<stack>
#include <algorithm>
#include <unordered_map>
#include "map"
using namespace std;
int FirstNotRepeatingChar(string str) {
if(str.size() == 1) return 0;
map<char, int> mp;
for(int i = 0; i < str.size(); ++i)
mp[str[i]]++;
for(int i = 0; i < str.size(); ++i){
if(mp[str[i]]==1)
return i;
}
return -1;
}
int main() {
string str = "google";
int res = FirstNotRepeatingChar(str);
cout << res;
return 0;
}