剑指Offer:字符流中第一个不重复的字符(java版)

博客围绕找出字符流中第一个只出现一次的字符展开。介绍了两种实现方法,一是借助byte[128]数组和StringBuffer等辅助空间,二是只借助数组,通过设置数组值标记字符出现情况,最后阐述了获取首现一次字符的原理。

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

题目描述

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

借助数组和另一辅助空间

首先用一个byte[128]数组来记录出现过的字符(因为字符为1个字节,最多为128)
然后用一个StringBuffer存储只出现过一次的字符(从前到后就是它们依次出现的顺序),如果发现重复出现了,就从StringBuffer中删除这个字符。
FirstAppearingOnce()只需要返回StringBuffer的0位置上的字符即可。
同理,这个StringBuffer可以换成其他的容器,如List,HashMap等

public class Solution {
    //Insert one char from stringstream
    private byte[] bt = new byte[128];
    StringBuffer st = new StringBuffer();
    public void Insert(char ch){
        if(bt[ch]==0){ // 第一次出现
            bt[ch]++; 
            st.append(ch); // 添加到st中
        }else if(bt[ch]==1){ // 第二次出现
            bt[ch]++;
            String s = ch+"";
            int index = st.indexOf(s);
            st.deleteCharAt(index); // 从st中删除
        }else{
            bt[ch]++;
        }
    }
  //return the first appearence once char in current stringstream
    public char FirstAppearingOnce(){
        if(st.length()==0) return '#';
        return st.charAt(0);
    }
}

只借助数组

如果第一次出现,将bt[ch]设置为index(字符出现的顺序),是大于0的,
如果重复出现了,就将bt[ch]设置为-1.
FirstAppearingOnce()的原理是,每次遍历数组,得到值大于0且index最小的那个位置i,再把i强转为char类型,就是要返回的字符

public class Solution {
    //Insert one char from stringstream
    private byte[] bt = new byte[128];
    byte index = 1;
    public void Insert(char ch){
        if(bt[ch]==0){
            bt[ch] = index;
        }else if(bt[ch]>0){
            bt[ch] = -1;
        }
        index++;
    }
  //return the first appearence once char in current stringstream
    public char FirstAppearingOnce(){
        int min = Integer.MAX_VALUE;
        char res = '\0';
        for(int i =0;i<128;i++){
            if(bt[i]>0 && bt[i]<min){
                min = bt[i];
                res = (char)i;
            }
        }
        if(res =='\0') return '#';
        return res;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值