解题思路:
对于这个题,首先先定义一个数字数组,用来记录26个字目出现的次数,记录完后再遍历字符串,找到第一个值为1的就返回。
值得注意的是 :遍历字符串的时候,应该判断的是count[s[i] - 'a'] 即要判断的字符减去’a'得到的值作为count数组的下标,然后判断下标对应的内容是否为1.
#include<iostream>
#include<string>
using namespace std;
int firstUniqChar(string s)
{
int count[26] = { 0 };
for (auto & i : s)
{
count[i - 'a']++;
}
for (int i = 0; i < s.size(); i++)
{
if (count[s[i] - 'a'] == 1)
{
return i;
}
}
return -1;
}
int main()
{
string s("hapy hai");
cout << firstUniqChar(s);
system("pause");
return 0;
}