zoukankan      html  css  js  c++  java
  • 找出字符流中第一个只出现一次的字符

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

     1 class Solution
     2 {
     3 
     4     // 方法一:
     5     #if false
     6     // 字典的键值存放字符和出现的次数
     7     private Dictionary<char, int> dict = new Dictionary<char,int>();
     8 
     9     public char FirstAppearingOnce()
    10     {
    11         // write code here
    12         // 遍历字典,第一个Value为1的Key为所求
    13         foreach (var item in dict)
    14         {
    15             if (item.Value == 1)
    16             {
    17                 return (char)item.Key;
    18             }
    19         }
    20 
    21         return '#';
    22     }
    23 
    24     public void Insert(char c)
    25     {
    26         // write code here
    27         // 字典为空,加入第一个键值
    28         if (dict == null)
    29         {
    30             dict.Add(c, 1);
    31             return;
    32         }
    33 
    34         // 字典是否存在键值c,默认false
    35         bool flag = false;
    36 
    37         if (dict.ContainsKey(c))
    38         {
    39             dict[c] += 1;
    40         }
    41         else
    42         {
    43             dict.Add(c, 1);
    44         }
    45     }
    46     #endif
    47 
    48     // 方法二:
    49     /* 申请一个整数数组,大小为256,int[] count = new int[256]{0};
    50      * 初始化值全为 0
    51      * 以输入字符的值作为数组下标,在对应的位置存入出现次数,
    52      * 声明一个字符列表,记录输入字符的顺序         *
    53      */
    54     private int[] count = new int[256];
    55 
    56     private List<char> list = new List<char>();
    57 
    58     public void Insert(char ch)
    59     {
    60         // Write code here
    61 
    62         // 如果当前字符第一次出现,记录出现顺序
    63         if (count[(int) ch] == 0)
    64             list.Add(ch);
    65 
    66         count[(int) ch]++;
    67     }
    68 
    69     public char FirstAppearingOnce()
    70     {
    71         // Write code here
    72 
    73         foreach (var item in list)
    74         {
    75             if (count[(int) item] == 1)
    76             {
    77                 return (char) item;
    78             }
    79         }
    80 
    81         return '#';
    82     }
    83 }
  • 相关阅读:
    linux——03-DevOps实战(详版)
    总结跟语言无关的东西
    drf—— RBAC-基于角色的访问控制
    drf—— 全局异常
    122买卖股票的最佳时机
    还记得这门古老的编程语言么,送你一份perl书单!
    程序员学习必备书单汇总,超全!
    书单来了!大厂的技术牛人在读什么:阿里篇
    书单来了!大厂的技术牛人在读什么:华为篇
    书单来了!大厂的技术牛人在读什么:腾讯篇
  • 原文地址:https://www.cnblogs.com/xiaolongren/p/12157659.html
Copyright © 2011-2022 走看看