字符流中第一个只出现一次的字符

一、题目

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

二、问题分析

字符只能一个接着一个从字符流中读出来。用字符的ASCII码作为哈希表的键值,而把字符对应的位置作为哈希表的值。
当一个字符第一次从字符中读出来时,把它在字符流中的位置保存在数据容器(哈希表)中。
当这个字符再次从字符流中读出时,那么它就不是只出现一次的字符,也就可以被忽略了。
这是把它在哈希表中保存的值更新为一个特殊的值(如负数值-2)。

#include <cstdio>
#include <vector>
#include <limits>

using namespace std;

class CharStatistics
{
public:
    CharStatistics() : index(0)
    {
        for(int i = 0; i < 256; ++i)
            occurrence[i] = -1;  // init: The character has not found;
    }

    void Insert(char ch)
    {
        if(occurrence[ch] == -1)  //第一次从字符流中读出
            occurrence[ch] = index;  //更新为它在字符流中的位置
        else if(occurrence[ch] >= 0) //字符再次从字符流中读出时
            occurrence[ch] = -2;

        index++;
    }

    /* 扫描整个数组,从中找到最小的>=0的值对应的字符 */
    char FirstAppearingOnce()
    {
        char ch = '';
        int minIndex = numeric_limits<int>::max();
        for(int i = 0; i < 256; ++i)
        {
            if(occurrence[i] >= 0 && occurrence[i] < minIndex)
            {
                ch = (char) i;
                minIndex = occurrence[i];
            }
        }

        return ch;
    }

private:
    /* occurrence[i]: A character with ASCII value i;
     * occurrence[i] = -1: The character has not found;
     * occurrence[i] = -2: The character has been found for mutlple times
     * occurrence[i] >= 0: The character has been found only once
     */
    int occurrence[256];
    int index;
};
作者:yusq77

-------------------------------------------

Wish you all the best and good health in 2021.

原文地址:https://www.cnblogs.com/yusq77/p/13546474.html