NO-54、字符流中第一个不重复的字符

这篇博客介绍了两种方法来查找字符流中第一个只出现一次的字符。第一种方法利用了C++的vector和count函数,第二种方法则借助了unordered_map。在字符流中,每次插入一个字符后,可以通过遍历容器并统计每个字符出现的次数来找到第一个只出现一次的字符。这两种解法都提供了高效的解决方案。
摘要由CSDN通过智能技术生成

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

class Solution
{
public:
  //Insert one char from stringstream
    //对于字符串要求不重复,返回第一个不重复的字符串
    void Insert(char ch) {
        v.push_back(ch);//将元素添加到vector动态数组中,先把元素添加到vector中
         
    }
  //return the first appearence once char in current stringstream
    char FirstAppearingOnce() {
        if(v.empty())return '#';
        for(auto &ch:v){//auto可以在声明变量的时候根据变量初始值的类型自动为此变量选择匹配的类型
            if(count(v.begin(),v.end(),ch)==1)return ch;//count统计某一值在一定范围内出现的次数
        }
        return '#';
    }
    vector<char>v;

};

count函数原型-统计某一值在一定范围内出现的次数

template <class InputIterator, class T>  
typename iterator_traits<InputIterator>::difference_type 
count (
InputIterator first, 
InputIterator last, 
const T& val
);

解法2:借助unordered_map

class Solution
{
public:
  //Insert one char from stringstream
    void Insert(char ch) {//先把每个字符串按照字母插入进去
         v.push_back(ch);
         unmp[ch]++;
    }
  //return the first appearence once char in current stringstream
    char FirstAppearingOnce() {
        for(auto &ch:v){
            if(unmp[ch]==1)return ch;
        }
        return '#';
    }
    vector<char>v;
    unordered_map<char, int>unmp;

};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值