• 54、剑指offer--字符流中第一个不重复的字符


    题目描述
    请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。 
    输出描述:
    如果当前字符流没有存在出现一次的字符,返回#字符。
     
    解题思路:采用哈希表来实现。用字符的ASCII嘛作为哈希表的键值,而把字符对应的位置作为哈希表的值。遍历所有字母,如果该字母出现1次,且该字符对应的位置<minIndex,更新minIndex
    其中-1表示未出现过,-2表示多次出现,0表示只出现一次
     1 class Solution
     2 {
     3 public:
     4     Solution():index(0)
     5     {
     6         for(int i=0;i<256;i++)
     7             occurence[i] = -1;
     8     }
     9   //Insert one char from stringstream
    10     void Insert(char ch)
    11     {
    12         if(occurence[ch] == -1)
    13             occurence[ch] = index;
    14         else if(occurence[ch] >= 0)
    15             occurence[ch] = -2;
    16         index++;
    17     }
    18   //return the first appearence once char in current stringstream
    19     char FirstAppearingOnce()
    20     {
    21         char ch = '';
    22         int minIndex = numeric_limits<int>::max();//返回编译器允许的int型数 最大值
    23         for(int i=0;i<256;i++)
    24         {
    25             if(occurence[i] >=0 && occurence[i] <minIndex)//minIndex表示在字符串中出现的位置
    26             {
    27                 ch = (char)i;
    28                 minIndex = occurence[i];//i存储的是字符串的acii码,数组occ[i]存储的是位置,多次就是-2,没出现就是-1
    29             }
    30         }
    31          if(ch == '')//如果当前字符流没有存在出现一次的字符,返回#字符。
    32             return '#';
    33         return ch;
    34     }
    35 private:
    36     int occurence[256];//其中数组下标i对应与ASCII码
    37     int index;//存储第一个只出现一次的字符的索引
    38  
    39 };
  • 相关阅读:
    asp+access win2008php+mysql /dedecms 配置总结
    js获取页面元素位置函数(跨浏览器)
    Extjs 4 小记
    小总结
    新浪微博 page应用 自适应高度设定 终于找到解决方法
    常用的三层架构设计(转载)
    http://www.jeasyui.com/
    http://j-ui.com/
    日期编辑器MooTools DatePicker
    android布局
  • 原文地址:https://www.cnblogs.com/qqky/p/7095180.html
Copyright © 2020-2023  润新知