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

    题目描述

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

    思路

    设置一个数组,记录每个字符的三种状态:未出现(0),出现一次(1),多次出现(-1)。
    设置一个队列,记录每次从字符流中读取时,尚未出现过的字符。
    查询当前已读取的字符流中第一个只出现一次的字符,需要判断队首字符状态,执行出列操作直至队首元素只出现过一次。
    

    时间复杂度O(1),空间复杂度O(1)。

    代码

    import java.util.Queue;
    import java.util.LinkedList;
    public class Solution {
        private int[] map = new int[256];
        private Queue<Character> queue = new LinkedList<Character>();
        //Insert one char from stringstream
        public void Insert(char ch) {
            if(map[ch] == 0) {
                map[ch] = 1;
                queue.offer(ch);
            } else if(map[ch] == 1) {
                map[ch] = -1;
            }
        }
      //return the first appearence once char in current stringstream
        public char FirstAppearingOnce() {
            while(!queue.isEmpty() && map[queue.peek()] == -1) {
                queue.poll();
            }
            if(!queue.isEmpty()) {
                return queue.peek();
            }
            return '#';
        }
    }
    

    笔记

  • 相关阅读:
    mysql
    MySQL主从同步
    python与各数据库的交互
    snmptrap
    web场景的监控
    zabbix的历史数据存储到elasticsearch中
    使用PopupWindow的实现步骤
    使用PopupWindow的实现步骤
    ListView及其ArrayAdapter的应用
    ListView及其ArrayAdapter的应用
  • 原文地址:https://www.cnblogs.com/ustca/p/12391123.html
Copyright © 2011-2022 走看看