34、剑指offer--第一个只出现一次的字符

题目描述
在一个字符串(1<=字符串长度<=10000,全部由大写字母组成)中找到第一个只出现一次的字符,并返回它的位置
 
解题思路:对于题目要求,想到的是对于每一个字符,记录它出现的次数,然后再一次遍历整个字符串,第一个出现次数为1的字符的位置即为所求。因此采用hash表的思想。对于一个字符将其ASCII码为数组下标所对应的值+1,即其ASCII码为数组下标对应的数组值为其在字符串中出现的次数。
 1 #include <iostream>
 2 #include <string>
 3 using namespace std;
 4 class Solution {
 5 public:
 6     int FirstNotRepeatingChar(string str) {
 7         int length = str.size();
 8         if(length <= 0)
 9             return -1;
10         const int hashSize = 256;
11         unsigned int hashTable[hashSize] = {0};
12         for(int i=0;i<length;i++)
13         {
14             hashTable[str[i]]++;
15         }
16         int i=0;
17         while(str[i] != '')
18         {
19             if(hashTable[str[i]] == 1)
20                 return i;
21             i++;
22         }
23         return -1;
24     }
25 };
26 
27 int main()
28 {
29     string s = "abaccdeff";
30     Solution ss;
31     int r;
32     r = ss.FirstNotRepeatingChar(s);
33     cout<<r<<endl;
34     return 0;
35 }
原文地址:https://www.cnblogs.com/qqky/p/6964840.html