字符流中第一个不重复的字符

题目描述

请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。

输出描述:

如果当前字符流没有存在出现一次的字符,返回#字符。

分析:第一反应肯定是找一个hash表把这个字符流以及出现的次数存下来,比如我用的就是两个vector,第一个vector按字符出现的顺序存下来,第二个按对应顺序存下来字符出现的次数。还有一种就是字符也就是256个,然后定义个长度为256的字符数组,我想到这儿的时候后面对出现的次数没想清楚,一开始是想到删掉重复的,后来想到删掉重复的如果第三次出现就雪崩,如果用字符值当数组下标,那里面应该存什么没有想清楚。剑指offer上面的思路很好,应该存字符出现的位置。然后用特殊的数字表示未出现和出现多次。

代码:

class Solution
{
public:
    vector<char> str;
    vector<int> count;
  //Insert one char from stringstream
    void Insert(char ch)
    {
         int i;
         for(i=0;i<str.size();i++){
             if(ch==str[i]){
                 count[i]++;
                 break;
             }
         }
        if(i==str.size()){
            str.push_back(ch);
            count.push_back(1);
        }
    }
  //return the first appearence once char in current stringstream
    char FirstAppearingOnce()
    {
        for(int j=0;j<count.size();j++){
            if(count[j]==1)
                return str[j];
        }
        return '#';
    }

};

 

剑指offer思路代码:

链接:https://www.nowcoder.com/questionTerminal/00de97733b8e4f97a3fb5c680ee10720
来源:牛客网

public class Solution {
    //Insert one char from stringstream
    private int[] occurence = new int[256];
    private int index;
    
    public Solution(){
        for(int i=0;i<256;i++){
            occurence[i] = -1;
        }
        index = 0;
    }
    void Insert(char ch)
    {
        if(occurence[ch] == -1)
            occurence[ch] = index;
        else if(occurence[ch] >= 0)
            occurence[ch] = -2;
        
        index++;
    }
  //return the first appearence once char in current stringstream
    char FirstAppearingOnce()
    {
        char ch = '\0';
        int minIndex = Integer.MAX_VALUE;
        for(int i=0;i<256;i++){
            if(occurence[i] >=0 && occurence[i]<minIndex){
                ch = (char)i;
                minIndex = occurence[i];
            }
        }
        if(ch == '\0')
            return '#';
        return ch;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值