[每日一道小算法(七十)][字符串] 字符流中第一个不重复的字符(剑指offer题)

前言:
关照自己的灵魂,注重自己的成长,跟别人学,同自己比,人生自然多了许多如意。

题目描述

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

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

题目解析

这道题我是使用队列来存储第一次出现的字符,如果字符出现超过了一次,则直接删除掉。存储字符的个数。我这个里使用的是数组。ACSII字符一共128个。所以这声明128大小的数组容量就可以实现。

代码样例

package com.asong.leetcode.FirstAppearingOnceInputStream;

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

/**
 * 字符流中第一个不重复的字符
 * 请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,
 * 当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。
 * 当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。
 */
public class Solution {
    int[] count = new int[128];
    //使用队列 存储不重复的字符
    Queue<Character> queue = new LinkedList<Character>();
    //Insert one char from stringstream
    public void Insert(char ch)
    {
        //存储并计数
        if(count[ch]++==0)
        {
            queue.add(ch);
        }
    }
    //return the first appearence once char in current stringstream
    public char FirstAppearingOnce()
    {
        Character character = null;
        while((character=queue.peek())!=null)
        {
            char c = character.charValue();
            if(count[c]==1)
            {
                return c;
            }else {
                queue.remove();
            }
        }
        return '#';
    }
}

发布了197 篇原创文章 · 获赞 73 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_39397165/article/details/104481935