387. First Unique Character in a String

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;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值