zoukankan      html  css  js  c++  java
  • 字符流中第一个不重复的字符

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

    题目描述

    请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"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
    **********************************/
    
  • 相关阅读:
    P1199三国游戏(博弈论)
    平方求和
    完全立方公式
    P1414 又是毕业季(数论)
    P1514 引水入城(搜索+线段完全覆盖)
    树莓派利用Django搭建聊天网页服务器 —— 准备篇
    树莓派下安装Django环境
    Linux终端光标消失问题
    OpenCV 简介
    树莓派是什么?能干什么?和单片机有什么区别?
  • 原文地址:https://www.cnblogs.com/hesper/p/10531739.html
Copyright © 2011-2022 走看看