【简单】面试题50. 第一个只出现一次的字符(*)

643 篇文章 5 订阅

【题目】
在字符串 s 中找出第一个只出现一次的字符,如果没有,返回一个单空格,s 只包含小写字母。您返回的结果必须是这几个值中的一个 {“Sunday”,
来源:leetcode
链接:https://leetcode-cn.com/problems/di-yi-ge-zhi-chu-xian-yi-ci-de-zi-fu-lcof/
【示例】
s = “abaccdeff”
返回 “b”
【示例2】
s = “”
返回 " "
【代码】

class Solution {
public:
    char firstUniqChar(string s) {
        if(s=="")
            return ' ';
        s+=" ";
        int len=s.size();
        for(int i=0;i<len;i++)
            if(s.find(s[i],i+1)==-1&&s.find(s[i])==i)
                return s[i];        
        return ' ';
    }
};

【方法二】

class Solution {
private:
    map<char,int> m;
public:
    char firstUniqChar(string s) {
       for(auto x:s)
            m[x]++;
        for(auto x:s)
            if(m[x]==1)
                return x;
        return ' ';
    }
};

【方法三】

static int n=[](){
 
    std::ios::sync_with_stdio(false);
 
    std::cin.tie(nullptr);
 
    return 0;
 
}();
class Solution {
private:
    const static int SIZE = 26;
    // 第一次出现的位置
    int firstIndex[SIZE];
public:
    char firstUniqChar(string s) {
        if (s == "") {
            return ' ';
        }
        // 初始化
        memset(firstIndex, -1, SIZE * sizeof(int));
        for (int i = 0 ; i < s.size() ; i ++) {
            // 如果没有出现过
            if (firstIndex[s[i] - 'a'] < 0) {
                firstIndex[s[i] - 'a'] = i;
            } else {
                // 出现过的话,将下标置为max
                firstIndex[s[i] - 'a'] = INT_MAX;
            }
        }
        int resutIndex = INT_MAX;
        char resultChar;
        for (int i = 0 ; i < SIZE ; i ++) {
            if (firstIndex[i] < resutIndex && firstIndex[i] >= 0) {
                resutIndex = firstIndex[i];
                resultChar = 'a' + i;
            }
        }
        if (resutIndex == INT_MAX) {
            return ' ';
        }
        return resultChar;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值