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

来源:互联网 发布:javac 多个java文件 编辑:程序博客网 时间:2024/06/03 23:08

时间限制:1秒 空间限制:32768K 热度指数:34735
本题知识点: 字符串

题目描述
请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符”go”时,第一个只出现一次的字符是”g”。当从该字符流中读出前六个字符“google”时,第一个只出现一次的字符是”l”。
输出描述:
如果当前字符流没有存在出现一次的字符,返回#字符。

题解:应用哈希表的思想,将字符串中的每一个字符对应到哈希表中(前提是:字符的范围是有限的),在读取每一个字符的同时,将哈希表中对应的字符+1,在得到输出第一个不重复的字符的时候,遍历字符串,如果遇到第一个哈希表的值为1的时候,将对应的字符输出。不能遍历哈希表,因为,如果从头遍历哈希表的时候可能出现 在后面出现的字符首先出现 的情况。

#include<stdio.h>#include<string>#include<iostream>using namespace std;class Solution{public:    Solution()    {        str = "";        for (int i = 0; i<256; i++)            hash[i] = 0;    }    //Insert one char from stringstream    void Insert(char ch)    {        str += ch;        hash[(int)ch]++;    }    //return the first appearence once char in current stringstream    char FirstAppearingOnce()    {        int len = str.length();        for (int i = 0; i<len; i++)        {            if (hash[(int)str[i]] == 1)            {                return str[i];            }        }        return '#';    }private:    string str;    int hash[256];};int main(void){    Solution Sol;    Sol.Insert('g');    cout<<Sol.FirstAppearingOnce();    return 0;}