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

  1. 题目描述
    1. 输出描述:

题目描述

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

输出描述:

  • 如果当前字符流没有存在出现一次的字符,返回#字符。
  • 空间换时间
class Solution
{
public:
    // 哈希思想存储
    int chars[127] = {0};
    string str = ""; 
  //Insert one char from stringstream
    void Insert(char ch)
    {
        str += ch;// 存储字符流
         if (chars[ch] == 0){
             chars[ch]++;
         } else if(chars[ch] == 1){
             chars[ch] = -2;// 出现了多次
         }
    }
  //return the first appearence once char in current stringstream
    char FirstAppearingOnce()
    {
        for (int i = 0;i < str.length();++i) {
            if (chars[str[i]] == 1) {
                return str[i];
            }
        }
        return '#';
    }

};

转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 1056615746@qq.com

💰

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

Count:220

Author:攀登

Created At:2019-12-26, 23:12:31

Updated At:2024-06-15, 15:53:35

Url:http://jiafeimao-gjf.github.io/2019/12/26/sword-%E5%AD%97%E7%AC%A6%E6%B5%81%E4%B8%AD%E7%AC%AC%E4%B8%80%E4%B8%AA%E4%B8%8D%E9%87%8D%E5%A4%8D%E7%9A%84%E5%AD%97%E7%AC%A6/

Copyright: 'Attribution-non-commercial-shared in the same way 4.0' Reprint please keep the original link and author.

×

Help us with donation