头图

JZ-054 - first non-repeating character in character stream

雄狮虎豹
中文

The first unique character in the character stream

Topic description

Please implement a function to find the first one-occurrence character in the character stream. For example, when only the first two characters "go" are read from the character stream, the first character that occurs only once is "g". When reading the first six characters "google" from this character stream, the first character that occurs only once is "l".

title link : first non-repeating character in character

code

import java.util.LinkedList;
import java.util.Queue;

/**
 * 标题:字符流中第一个不重复的字符
 * 题目描述
 * 请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,
 * 第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。
 * 题目链接:
 * https://www.nowcoder.com/practice/00de97733b8e4f97a3fb5c680ee10720?tpId=13&&tqId=11207&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
 */
public class Jz54 {

    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();
    }

    public static void main(String[] args) {

    }
}
[Daily Message] May your bad mood last night be gone when you lift the quilt and open the curtains today.
阅读 703

LeetCodet题解
技术学习

玉树临风,仙姿佚貌!

1.7k 声望
7.1k 粉丝
0 条评论

玉树临风,仙姿佚貌!

1.7k 声望
7.1k 粉丝
文章目录
宣传栏