字符串中的第一个唯一字符
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
示例:
s = “leetcode”
返回 0
s = “loveleetcode”
返回 2
提示:
你可以假定该字符串只包含小写字母。
思路:
记录每个字母出现的次数以及第一次出现的位置索引,最后进行比较。
代码:
class Solution {
public:
int firstUniqChar(string s) {
int count[26][2]={0}; //每个字母出现的次数,第一次出现的索引
for(int i=0;i<s.length();i++)
{
if(count[s[i]-'a'][0]++==0)
count[s[i]-'a'][1]=i;
}
int ind=INT_MAX;
for(int i=0;i<26;i++)
{
if(count[i][0]==1)
{
ind=count[i][1]<ind?count[i][1]:ind;
}
}
if(ind==INT_MAX)
return -1;
return ind;
}
};
结果: