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;
}
};