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:
class Solution {
public:
int firstUniqChar(string s) {
vector<char> yet;
for(int i=0;i<s.size();i++){
if(find(yet.begin(),yet.end(),s[i])==yet.end()){
yet.push_back(s[i]);
if( find(s.begin()+i+1,s.end(),s[i]) == s.end() ){
return (i);
}
}
}
return (-1);
}
};
代码2:
class Solution {
public:
int firstUniqChar(string s) {
set<char> ss;
for(int i=0;i<s.size();i++){
char ch=s[i];
if(ss.count(ch)){continue;}
else{ss.insert(ch);}
if((find(s.begin()+i+1,s.end(),ch)==s.end()) ){return i;}
}
return -1;
}
};
代码3:
class Solution {
public:
int firstUniqChar(string s) {
vector<int> count(26, 0);
for(int i=0;i<s.length();i++){
int cidx = s[i] - 'a';
//记录位置,为了防止,同时做标记,假如出现两次,即大于零(所以对于0位置,针对性加一),变为-1
if(count[cidx]==0) count[cidx] = i + 1;
else count[cidx] = -1;
}
int idx = INT_MAX;
for(int i=0;i<26;i++){
if(count[i]>0 && count[i]<idx){
idx = count[i];
}
}
return idx==INT_MAX?-1:idx-1;
}
};