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

当从字符流中只读出前两个字符“go”时,第一个只出现一次的字符是‘g’。当从该字符流中读出前六个字符“google”时,第一个只出现 1 次的字符是”l”。


首先要记录一个字符出现的次数,为了实现O(1)查找,使用简易hash表存储。用occurences[256] 记录字符出现的次数。设置:
occurences[i] = 0, 该字符未出现;
occurences[i] = 1, 该字符出现一次;
occurences[i] = 2, 该字符出现2次或大于2次
使用先进先出的队列记录,出现一次的字符。在后面的字符输入过程中,可能会输入一个已经存在一次的字符,队列里可能存在不止出现一次的字符,因此在取队列顶元素时,应再次检查该元素是否出现1次,如果不是,则队列pop,直至找到一个只出现一次的字符索引。

时间复杂度O(1)
空间复杂度:occurences[256] 空间恒定;队列最多只会存在256个字符(只会push第一次出现的字符)。因此空间复杂度O(1)

#include <iostream>
#include <queue>
using namespace std;
class CharStatics {
private:
    unsigned int occurences[256];
    int index;
    queue<int> index_queue;
public:
    CharStatics() {
        index = -1;
        for (int i = 0; i <= 255; i++)
            occurences[i] = 0;
    }
    void InsertChar(char ch) {
        if (occurences[ch] == 0) { 
            occurences[ch] = 1;  // 第一次出现,设置出现次数,压入队列
            index_queue.push(ch);
        } else {
            occurences[ch] = 2;// 第 2 次或多次出现
        } 
    }
    char FirstApperingOnce() {
        // 找到最先只出现一次的字符,并用index指向
        while (!index_queue.empty() && occurences[index_queue.front()] != 1) {
            index_queue.pop();
        }
        if (!index_queue.empty())
            index = index_queue.front();
        else
            index = -1; // 没有只出现一次的字符
        if (index == -1)
            return '\0';
        return index+'\0';
    }
};

int main() {
    CharStatics str;
    str.InsertChar('g');
    cout << str.FirstApperingOnce() << endl;
    str.InsertChar('o');
    cout << str.FirstApperingOnce() << endl;
    str.InsertChar('o');
    cout << str.FirstApperingOnce() << endl;
    str.InsertChar('g');
    cout << str.FirstApperingOnce() << endl;
    str.InsertChar('l');
    cout << str.FirstApperingOnce() << endl;
    str.InsertChar('e');
    cout << str.FirstApperingOnce() << endl;
}

输出:

g
g
g
NUL
l
l
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值