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

    题目描述

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

    输出描述:

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

    题目分析:我们需要判断字符是不是只出现了一次的, 在所有只出现了一次的字符中找到最先出现的。

    因为只有字符, 我们用hash[256]的值表示出现的索引。下标表示字符,初始化所有字符都未出现(-1), 如果第一次出现,就将其赋值为索引值。如果之前出现过了,就标记为-2.

     返回只出现一次且索引值最小的字符。

     1 class Solution
     2 {
     3 private:
     4     int ind[256];
     5     int index;
     6 public:
     7     Solution(){
     8         for (int i = 0; i < 256; i++) {
     9             ind[i] = -1;
    10         }
    11         index = 0;
    12     }
    13   //Insert one char from stringstream
    14     void Insert(char ch)
    15     {
    16         if (ind[ch] == -1)
    17              ind[ch] = index;
    18         else if (ind[ch] >= 0)
    19             ind[ch] = -2;
    20         index++;
    21     }
    22   //return the first appearence once char in current stringstream
    23     char FirstAppearingOnce()
    24     {
    25         char res = '#';
    26         int minindex = INT_MAX;
    27         for (int i = 0; i < 256; i++) {
    28             if (ind[i] >= 0) {
    29                 if (ind[i] < minindex) {
    30                     res = char(i);
    31                     minindex = ind[i];
    32                 }
    33             }
    34         }
    35         return res;
    36     }
    37 
    38 };
  • 相关阅读:
    Kuangbin带你飞 专题二十 斜率DP
    牛客每日一题3月
    2020 SWJTU-ICPC Training Round #2(18年福建省赛)部分题解
    codeforces每日一题31-40
    SWJTU校队训练&Codeforces&Atcoder&&牛客三月补题
    Kuangbin带你飞-专题九连通图
    POJ 3667 Hotel(线段树区间合并)
    AtCoder Beginner Contest 157(题解)
    2.22专项测试复盘
    2.21专项测试复盘
  • 原文地址:https://www.cnblogs.com/qinduanyinghua/p/11474918.html
Copyright © 2011-2022 走看看