描述
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
示例:
s = "leetcode"
返回 0
s = "loveleetcode"
返回 2
提示:你可以假定该字符串只包含小写字母。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/first-unique-character-in-a-string/
求解
class Solution {
public:
// 暴力解法,遍历字符串中的每个字符,判断是否出现,且后面不再出现,时间复杂度O(N*N)
int firstUniqChar_vio(const string s) {
if (s.empty()) {
return -1;
}
const int N = s.size();
for (int i = 0; i < N; ++i) {
// 如果当前字符第一次出现且后面没有再出现,则满足
if (s.find_first_of(s[i]) == s.find_last_of(s[i])) {
return i;
}
}
return -1;
}
// 利用查找表实现,两次遍历,时间复杂度O(N)
int firstUniqChar(const string s) {
// 第一次遍历全部字符,记录数量
int record[26]{0};
for (const char c: s) {
++record[c - 'a'];
}
// 第二次遍历,返回第一个没有重复出现的下标
const int N = s.size();
for (int i = 0; i < N; ++i) {
if (record[s[i] - 'a'] == 1) {
return i;
}
}
return -1;
}
};