东寻

导航

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

题目描述

请实现一个函数用来找出字符流中第一个只出现一次的字符。
例如,当从字符流中只读出前两个字符"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 '#';
    }
}

笔记

posted on 2020-03-01 18:11  东寻  阅读(412)  评论(0编辑  收藏  举报