【Offer】[50-2] 【字符流中第一个只出现一次的字符】

题目描述

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

牛客网刷题地址

思路分析

  还是将数据存放在Map中,哈希表用数组occurrence实现。数组中的元素occurrence[i]和ASCII码的值为i的字符相对应。最开始的时候,数组中的所有元素都初始化为-1。当一个ASCII码为i的字符第一次从字符流中读出时,occurrence[i]的值 更新为它在字符流中的位置。当这个字符再次从字符流中读出时(occurrence[i]大 于或者等于0),occurrence[j]的值 更新为-2。当我们需要找出到目前为止从字符流里读出的所有字符中第一个不重复的字符时,只需要扫描整个数组,并从中找出最小的大于等于0的值对应的字符即可。这就是函数FirstAppearingOnce的功能。

测试用例

  1. 功能测试:读入一个字符;读入多个字符;读入的所有字符都是唯一的;读入的所有字符都是重复出现的。
  2. 特殊输入测试:读入0个字符。

Java代码

public class Offer050_02 {
    public static void main(String[] args) {
        test1();
        test2();
        test3();

    }
    
    private int index;
    private int[] occurence;
    
    public Offer050_02() {
        index=0;
        occurence = new int[256];
        for(int i=0;i<256;i++) {
            occurence[i]=-1;
        }
    }

    // Insert one char from stringstream
    public void Insert(char ch) {
        if(occurence[(int)ch]==-1) {
            occurence[(int)ch]=index;   //第一次出现
        }else if(occurence[(int)ch]>=0) {
            occurence[(int)ch]=-2;   //已经出现过了
        }
        index++;
    }

    // return the first appearence once char in current stringstream
    public char FirstAppearingOnce() {
        int minIndex=Integer.MAX_VALUE;  //最大的integer
        char ch='#';
        for(int i=0;i<256;i++) {
            if(occurence[i]>=0 && occurence[i]<minIndex) {
                ch = (char) i;
                minIndex=occurence[i];
            }
        }
        return ch;
    }

    private static void test1() {
    }
    private static void test2() {
    }
    private static void test3() {
    }
}

代码链接

剑指Offer代码-Java

猜你喜欢

转载自www.cnblogs.com/haoworld/p/offer502-zi-fu-liu-zhong-di-yi-ge-zhi-chu-xian-yi-.html