- Total Accepted: 4516
- Total Submissions: 10603
- Difficulty: Easy
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.
分析:
题目的意思就是说找到首个不重复的字母!并且返回其位置,显然统计其位置就可以解决问题。
class Solution {
public:
int firstUniqChar(string s) {
map<char,int> mapping;
vector<int> record(26,0);
bool flag=true;
for(int i=0;i<s.size();i++)
record[s[i]-'a']++;//统计每个单词出现次数
for(int i=0;i<s.size();i++){
if(record[s[i]-'a']==1)//找到首个出现次数为1的,找到了就返回其位置
return i;
}
return -1;
}
};
注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!
原文地址:http://blog.youkuaiyun.com/ebowtang/article/details/52187799
原作者博客:http://blog.youkuaiyun.com/ebowtang
本博客LeetCode题解索引:http://blog.youkuaiyun.com/ebowtang/article/details/50668895
本文介绍了一种算法,用于找出字符串中第一个不重复的字符并返回其索引位置。通过使用映射表和记录向量来统计字符出现的次数,从而高效地解决此问题。
3059

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



