剑指offer:请实现一个函数用来找出字符流中第一个只出现一次的字符。

剑指offer算法题


字符串

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

输出描述:
如果当前字符流没有存在出现一次的字符,返回#字符。

题目分析
方法一 利用队列
因为ASCII 一共能表示256个字符,所以初始化一个长度为256的数组,其中每一个元素的下标即可代表一个字符。(实际ASCC II 只用了128个,所以初始化长度为128也可以。)
如果当前位置为0,则证明只出现了一次,然后添加到队列,并将当前位置的值置为1;
如果当前位置不为0,则证明已经出现过了,则将当前值+1。

在寻找的过程中对队列进行循环判断。如果队列首个元素为下表所在数组中的值为1,证明只出现了一次,则返回队列头,用peek();如果不是,则出队poll(),继续判断下一个。

下面是Java代码实现

import java.util.LinkedList;
import java.util.Queue;
public class Solution {
    //Insert one char from stringstream
    private int[] tmp = new int[256];
    private int first = 1;
    Queue<Character> q = new LinkedList<>();
    
    public void Insert(char ch)
    {
        if(tmp[ch] == 0){
            q.offer(ch);
            tmp[ch] = 1;
        }else{
            tmp[ch] +=1;
        }
        
    }
  //return the first appearence once char in current stringstream
    public char FirstAppearingOnce()
    {
        while(!q.isEmpty()){
        //找到了返回队列第一个,如果队列第一个不是出现了一次,则出队。
            if(tmp[q.peek()]==1){
                return q.peek();
            }else{
                q.poll();
            }
        }
        return '#';
    }
}

方法二 利用linkedhashmap
linkedhashmap既可以记录插入顺序,又可以记录每个字母插入次数。

下面是Java代码实现

import java.util.LinkedHashMap;
import java.util.Map;
public class Solution {
    //Insert one char from stringstream
    LinkedHashMap<Character, Integer> map = new LinkedHashMap<>();
    public void Insert(char ch)
    {
    	//字符如果插入过次数+1,没插入过次数设为1。
        if(map.containsKey(ch)){
            map.put(ch, map.get(ch)+1);
        }else{
            map.put(ch, 1);
        }
    }
  //return the first appearence once char in current stringstream
    public char FirstAppearingOnce()
    {
    //循环遍历,如果找到Value为1的,则为第一个出现的次数为1的字母。
        for(Map.Entry<Character , Integer> entry : map.entrySet()){
            if(entry.getValue() == 1){
                return entry.getKey();
            }
        }
        return '#';
    }
}

参考https://www.nowcoder.com/practice/00de97733b8e4f97a3fb5c680ee10720?tpId=13&&tqId=11207&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值