剑指offer系列27:第一个只出现一次的字符

这个题我一看到,就觉得map很适合,因为map最擅长做这种给字母计数,给单词计数之类的工作。我看到剑指offer上是用hash表做的,其实原理是一样的,但是由于C++中没有hash表的模板,所以我就用map做了。

 1 #include<iostream>
 2 #include<string>
 3 #include <map>
 4 //#include <vector>
 5 //#include <algorithm>
 6 //#include <sstream>
 7 using namespace std;
 8 class Solution {
 9 public:
10     int FirstNotRepeatingChar(string str) {
11         if (str.end() == str.begin())
12             return 0;
13         map<char, int> mp;
14         for (int i = 0; i < str.size();++i)
15             mp[str[i]]++;
16         for (int i = 0; i < str.size(); ++i)
17         {
18             if (mp[str[i]] == 1)
19                 return i;
20         }
21         return -1;
22     }
23 };
24 int main()
25 {
26     Solution so;
27     //vector<int> test{ 3,5,1,4,2 };
28     string test("abaccdeff");
29     cout << so.FirstNotRepeatingChar(test) << endl;
30     return 0;
31 }

 

转载于:https://www.cnblogs.com/neverland0718/p/11176218.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值