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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zxm1306192988/article/details/81987648

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

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

题解:

用 一个 int[] 数组记录字符出现的次数
用 一个队列,保留添加的字符。
每次添加一个字符后,就看队头是否有次数大于1的字符,如果有就出队。

最后,如果队列为空,则说明不存在出现一次的字符,返回# ,否则返回队头字符,即为第一个只出现一次的字符。

import java.util.LinkedList;
import java.util.Queue;
public class Solution {
    private int[] cnts = new int[256];// 记录字符出现的次数
    private Queue<Character> queue = new LinkedList<>();// 保留添加的字符

    // Insert one char from stringstream
    public void Insert(char ch) {
        cnts[ch]++;
        queue.add(ch);
        while (!queue.isEmpty() && cnts[queue.peek()] > 1) { // 弹出出现多次的字符
            queue.poll();
        }
    }

    // return the first appearence once char in current stringstream
    public char FirstAppearingOnce() {
        return queue.isEmpty() ? '#' : queue.peek();
    }
}

猜你喜欢

转载自blog.csdn.net/zxm1306192988/article/details/81987648