题目:
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,就返回对应索引。空间复杂度O(1),时间复杂度O(n)。
代码:
class Solution {
public:
int firstUniqChar(string s) {
vector<int> characters(26, 0);
for(int i = 0; i < s.length(); ++i) {
int index = s[i] - 'a';
++characters[index];
}
for(int i = 0; i < s.length(); ++i) {
int index = s[i] - 'a';
if(characters[index] == 1) {
return i;
}
}
return -1;
}
};