[Offer] [50-2] [character stream only appears once in the first characters]

Title Description

  Please implement a function to find the character stream for the first time a character appears only. For example, when the character stream reads only the first two characters "go", the first character only occurs once a "g". When reading out the first six characters "google" from the character stream, first appears only one character is "l".
  

Cattle brush off questions address network

Ideas analysis

  Or the data stored in the Map, the hash table to achieve an array occurrence. Occurrence character element [i] and the array of ASCII code corresponding to the value i. The very beginning, all the elements in the array are initialized to -1. ASCII code when a first character stream read from the character i, occurrence [i] is updated to the value of its position in the character stream. When this character is read out again from the character stream (occurrence [i] is greater than or equal to 0), occurrence [j] to update the value of -2. When we need to find all the characters so far read from the stream of characters in the first character is not repeated, only you need to scan the entire array, and to find the smallest value greater than or equal to 0 in the corresponding character. This is the function FirstAppearingOnce function.

Test Case

  1. Functional Test: A character is read; read more characters; all characters read is unique; all the characters read are recurring.
  2. Special input test: read 0 characters.

Java code

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() {
    }
}

Code link

Offer to prove safety codes -Java

Guess you like

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