Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.
Examples:
s = "leetcode"
return 0.
s = "loveleetcode",
return 2.
Note: You may assume the string contain only lowercase letters.
给定一字符串,找出其中第一个不重复的字母,返回其索引,若不存在则返回-1,这里假定所有的字符都是小写字母。
思路
由于输入只含有小写字母,则可构建字母数组以统计每个字母出现的次数。
class Solution {
public:
int firstUniqChar(string s) {
int res=-1;
int n=s.size();
if(n==1) return 0;
if(n<=0) return -1;
int a[26]={0};
for(int i=0;i<n;i++){
a[s[i]-'a']++;
}
for(int i=0;i<n;i++){
if(a[s[i]-'a']==1){
res=i;
break;
}
}
return res;
}
};