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

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

题目描述

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

输出描述:

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

有点益智意思, 是ASCII码表第一个字符, 只不过输出类似空格, 题目下面附带测试程序

class Solution
{
public:
  //Insert one char from stringstream
    void Insert(char ch)
    {
        // 记录每个字符出现次数
         str[ch-'']++;
        // 若第一次插入字母, 则把字符插入队列中
        if (1 == (str[ch-'']))
            myQueue.push(ch);
    }
  //return the first appearence once char in current stringstream
    char FirstAppearingOnce()
    {
        // 若子符不止出现一次, 则str[myQueue.front()必然大于1
        while((!myQueue.empty()) && (str[myQueue.front()] > 1))
            myQueue.pop();        // 弹出大于出现次数大于1的字符
        if (myQueue.empty())    // 若没有只出现一次的字符
            return '#';
        return myQueue.front();
    }
    
    int str[128];
    queue<char> myQueue;
};

构建256和数组, 哈希表原理, 和之前某一个题挺像

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

};

输出类似空格又不是空格

#include <iostream>
using namespace std;
int main() {
	cout << 'a' << endl;
	cout << (int)'a' << endl;
	cout << '' << endl;
	cout << 'a' - '' << endl;
	return 0;
}

/*************输出结果*************
a
97

97
**********************************/
原文地址:https://www.cnblogs.com/hesper/p/10531739.html