字符流中第一次出现的字符

本文介绍了一种在字符流中快速查找首个不重复字符的方法,通过使用HashMap和Queue实现O(1)时间复杂度的查询效率。代码示例展示了如何插入字符及返回首次出现的唯一字符。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一个简单的说明

    网上大多数的代码都是差不多的,它们的代码单次查询的时间复杂度是O(n),下面的代码时间复杂度是O(1)的,想想为什么?
    注意事项:不要被while欺骗了
package 字符流中第一个不重复的字符;

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

public class Solution {
    HashMap<Character, Integer> hms = new HashMap<Character, Integer>();
    // Insert one char from stringstream
    Queue<Character> q = new LinkedList<Character>();

    public void Insert(char ch) {
        if (hms.containsKey(ch)) {
            hms.put(ch, hms.get(ch) - 1);
        } else {
            hms.put(ch, -1);
            q.add(ch);
        }
    }

    // return the first appearence once char in current stringstream
    public char FirstAppearingOnce() {
        if (q.isEmpty()) {
            return '#';
        }
        while (!q.isEmpty()) {
            char ch = q.peek();
            if (hms.get(ch) < -1) {
                q.poll();
            } else {
                return ch;
            }
        }
        return '#';
    }

    public static void main(String[] args) {
        Solution s = new Solution();
        System.out.println(s.FirstAppearingOnce());
        s.Insert('g');
        s.Insert('o');
        System.out.println(s.FirstAppearingOnce());
        s.Insert('o');
        s.Insert('g');
        System.out.println(s.FirstAppearingOnce());
        s.Insert('l');
        s.Insert('e');
        System.out.println(s.FirstAppearingOnce());

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值