剑指Offer——字符流中第一个不重复的字符

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

http://www.nowcoder.com/questionTerminal/00de97733b8e4f97a3fb5c680ee10720

用数组存字符数量
用队列存出现单一次数的字符,如果字符出现了两次则从队列中移除该字符
查看第一个只出现一次的字符时直接取队首,如果队首为空则取#

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

/**
 * 请实现一个函数用来找出字符流中第一个只出现一次的字符。
 * 例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。
 * 当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。
 * 输出描述:
 * 如果当前字符流没有存在出现一次的字符,返回#字符。
 *
 * @author Ikaros
 * @date 2020/5/8 18:52
 */
public class 字符流中第一个不重复的字符 {
    int[] chars = new int[256];
    Queue<Character> queue = new LinkedList<>();

    //Insert one char from stringstream
    public void Insert(char ch) {
        if (++chars[ch] == 1) {
            queue.add(ch);
        } else {
            queue.remove(ch);
        }
    }

    //return the first appearence once char in current stringstream
    public char FirstAppearingOnce() {
        return queue.peek() == null ? '#' : queue.peek();
    }
}
全部评论

相关推荐

11-27 16:41
门头沟学院 Java
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务