leetcode 387.字符串中的第一个唯一字符
题目描述
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
案例:
s = “leetcode”
返回 0.
s = “loveleetcode”,
返回 2.
解题思路
建立一个数组统计每个字母的出现次数,再次遍历,查找第一个次数为1的元素。
class Solution {
public:
int firstUniqChar(string s) {
int status[26] = {0}; // 建立26个字符的次数表
// 统计每个字符出现的次数
for(int i=0; i<s.size(); i++){
status[s[i]-'a'] += 1;
}
// 重新从字符串的头部开始遍历,如果在状态表中的次数为1,则是第一个出现的唯一的字符
for(int i=0; i<s.size(); i++){
if(status[s[i]-'a'] == 1){
return i;
}
}
return -1;
}
};
采用内置函数的方法,string中的find_first_of和find_last_of函数,寻找第一出现的字符和最后一个出现的字符的下标,如果相等表示只有一个
class Solution {
public:
int firstUniqChar(string s) {
for(int i=0; i<s.size(); i++){
if(s.find_first_of(s[i]) == s.find_last_of(s[i])){
return i;
}
}
return -1;
}
};
欢迎大家关注我的个人公众号,同样的也是和该博客账号一样,专注分享技术问题,我们一起学习进步