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

解题思路1:

import java.util.*;
public class Solution {
    
    //用于存储不重复字符的队列,队首字符就是目前队列中第一个不重复的字符
    public Queue<Character> queue = new LinkedList<>();
    //用来记录每个字符出现的次数,根据ASCII表可知,一共只有127个字符,固然定义数组长度为127
    public int[] strs = new int[127];
    
    //Insert one char from stringstream
    public void Insert(char ch)
    {
        //记录ch字符的出现次数
        strs[ch]++;
        //将ch插入queue中
        queue.add(ch);
        //判断队首字符是否重复,若重复则从queue中移除
        while(!queue.isEmpty() && strs[queue.peek()] > 1){
            //将队首字符删除
            queue.poll();
        }
    }
    
    //return the first appearence once char in current stringstream
    public char FirstAppearingOnce()
    {
        //若queue不为空,则返回队首字符,即第一个不重复字符;否则返回‘#’
        return queue.isEmpty() ? '#' : queue.peek();
    }
}

解题思路2:

public class Solution {
    
    //用来记录每个字符出现的次数,根据ASCII表可知,一共只有127个字符,固然定义数组长度为127
    int[] strs = new int[127];
    //用来判断优先级,即出现的早晚
    int[] priority = new int[127];
    int count = 0;
    
    //Insert one char from stringstream
    public void Insert(char ch)
    {
        //记录ch字符的出现次数
        strs[ch]++;
        //保存ch第一次出现时对应的count值,count值越小,表示出现的越早
        if(priority[ch] == 0){
            
            //保存ch第一次出现时对应的count值
            priority[ch] = count;
            //自增
            count++;
        }
    }
    //return the first appearence once char in current stringstream
    public char FirstAppearingOnce()
    {
        //第一个不重复的字符
        char c = '#';
        //优先级
        int pri = 999;
        
        //计算第一个不重复的字符
        for(int i = 0 ; i < strs.length ; i++){
            //表示i字符只出现一次
            if(strs[i]==1){
                if(priority[i] < pri){
                    //i字符对应的优先级赋值给pri
                    pri = priority[i];
                    //当前第一个不重复的字符
                    c = (char)i;
                }
            }
        }
        
        return c;
    }
}

解题思路3:

import java.util.*;
public class Solution {
    //Insert one char from stringstream
    //256大小的数组来实现一个简易的哈希表
    int[] hastable = new int[256];
    StringBuffer s = new StringBuffer();
    public void Insert(char ch)
    {
        //字符添加到s中
        s.append(ch);
        hastable[ch]++;
    }
  //return the first appearence once char in current stringstream
    public char FirstAppearingOnce()
    {
        char[] chars = s.toString().toCharArray();
        
        for(char c : chars){
            if(hastable[c] == 1){
                return c;
            }
        }
        
        return '#';
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值