Prove safety Offer: The first character stream without repeating characters (java version)

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".

With arrays, and other auxiliary space

First, with a byte [128] array to record characters across (because the character is one byte, a maximum of 128)
and with a storage StringBuffer characters appear only once (from front to back is that they appear sequentially), If a duplicate is found there, then delete the characters from the StringBuffer.
FirstAppearingOnce () only needs to return to the character on the StringBuffer 0 position.
Similarly, this StringBuffer can be replaced with other containers, such as List, HashMap, etc.

public class Solution {
    //Insert one char from stringstream
    private byte[] bt = new byte[128];
    StringBuffer st = new StringBuffer();
    public void Insert(char ch){
        if(bt[ch]==0){ // 第一次出现
            bt[ch]++; 
            st.append(ch); // 添加到st中
        }else if(bt[ch]==1){ // 第二次出现
            bt[ch]++;
            String s = ch+"";
            int index = st.indexOf(s);
            st.deleteCharAt(index); // 从st中删除
        }else{
            bt[ch]++;
        }
    }
  //return the first appearence once char in current stringstream
    public char FirstAppearingOnce(){
        if(st.length()==0) return '#';
        return st.charAt(0);
    }
}

With only an array

If the first time, the bt [ch] is set index (sequence of characters that appear), is greater than 0,
if repeated, and it will bt [ch] is set to -1.
Principles FirstAppearingOnce () it is, per times through the array, that give the minimum value is greater than 0 and the position index i, then i strongly into char type, the character is to be returned

public class Solution {
    //Insert one char from stringstream
    private byte[] bt = new byte[128];
    byte index = 1;
    public void Insert(char ch){
        if(bt[ch]==0){
            bt[ch] = index;
        }else if(bt[ch]>0){
            bt[ch] = -1;
        }
        index++;
    }
  //return the first appearence once char in current stringstream
    public char FirstAppearingOnce(){
        int min = Integer.MAX_VALUE;
        char res = '\0';
        for(int i =0;i<128;i++){
            if(bt[i]>0 && bt[i]<min){
                min = bt[i];
                res = (char)i;
            }
        }
        if(res =='\0') return '#';
        return res;
    }
}

Guess you like

Origin blog.csdn.net/qq_43165002/article/details/90378708