53.字符流中第一個不重複的字符《劍指Offer》(Java版)

題目描述

請實現一個函數用來找出字符流中第一個只出現一次的字符。例如,當從字符流中只讀出前兩個字符"go"時,第一個只出現一次的字符是"g"。當從該字符流中讀出前六個字符“google"時,第一個只出現一次的字符是"l"。

輸出描述:

如果當前字符流沒有存在出現一次的字符,返回#字符。

 

 

 

import java.util.*;

public class Solution {
    Queue<Integer> queue = new LinkedList<>();
    int[] appeared = new int[256];

    //Insert one char from stringstream
    public void Insert(char ch) {
        if (appeared[ch] == 0) {
            appeared[ch] = 1;
            queue.add((int) ch);
        } else {
            appeared[ch] = 2;
            int size = queue.size();
            while (size-- != 0) {
                int peek = queue.peek();
                if (appeared[peek] != 1) {
                    queue.remove();
                } else {
                    break;
                }
            }
        }

    }

    //return the first appearence once char in current stringstream
    public char FirstAppearingOnce() {
        int size = queue.size();
        if (size == 0) {
            return '#';
        } else {
            return (char) (int) queue.peek();
        }

    }
}

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章