Given a string, find the first non-repeating character in it and return it’s index. If it doesn’t exist, return -1.

Examples:

1
2
3
4
5
s = "leetcode"
return 0.
s = "loveleetcode",
return 2.

思路

非常直白的方法,利用26元素的数组充当一个字典,统计一下字符出现的次数即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
int firstUniqChar(string s) {
if (s.length() == 0) return -1;
int stats[26] = {0};
for(int i = 0; i<s.length(); i++){
char tmp = s[i];
stats[s[i] - 'a'] += 1;
}
for(int i = 0; i<s.length(); i++){
char tmp = s[i];
if (stats[s[i] - 'a'] == 1) return i;
}
return -1;
}
};