在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).
思路:建立哈希表
#include<iostream>
#include<string>
#include<map>
using namespace std;
int main()
{
string str;
getline(cin,str);
cout<<"Out:"<<str<<endl;
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){
cout<<"字符第一个出现一次位置:"<<i;
}
}
return 0;
}
知识点:哈希表
std::map<std::string, size_t> people;
第 1 个模板类型参数指定键的类型是字符串,第 2 个模板类型参数指定值的类型为 size_t。