题目:
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;
}
};
本文介绍了一种高效算法,用于查找给定字符串中的第一个不重复字符及其索引位置。通过两次遍历字符串,该算法能在O(n)时间内完成任务,并保持O(1)的空间复杂度。
332

被折叠的 条评论
为什么被折叠?



