剑指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 }

 

posted @ 2019-07-12 15:14  妮妮熊  阅读(114)  评论(0编辑  收藏  举报