一、问题描述
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.
二、 思路
找到字符串中只出现一次的字符,这个字符是字符串最早出现的。由于只有小写字母,所以只要建一个26个字母的哈希表即可,统计字符出现的次数。
三、代码
class Solution {
public:
int firstUniqChar(string s) {
int hash[26] = {0};
for(int i = 0; i < s.size();++i){
hash[s[i] - 'a']++;
}
int i;
for(i = 0; i < s.size(); ++i){
if(hash[s[i] - 'a'] == 1){
return i;
}
}
return -1;
}
};