class Solution {
public:
int firstUniqChar(string s) //暴力解法
{
int size = s.size();
for (int i = 0; i < size; ++i)
{
int flag = 1;
for (int j = 0; j < size; ++j)
{
if ((s[i] == s[j]) && (i != j))//如果有相同的字符,就结束这轮对比
{
flag = 0;
break;
}
}
if (flag == 1)//循环走完,标志没有被改变,说明没有相同的字符
return i;
}
return -1;
}
};
class Solution {
public:
int firstUniqChar(string s) //计数排序解法
{
int count[26] = {0};//创建数组映射存储次数,初始化为 0
int size = s.size();
for (int i = 0; i < size; ++i)//第一次遍历,记录次数
{
++count[s[i] - 'a'];
}
for (int i = 0; i < size; ++i)//第二次遍历,找到第一个只出现一次的字母
{
if (count[s[i] - 'a'] == 1)
return i;
}
return -1;//走到这里说明不存在
}
};