Sword refers to offer—50_2. The first non-repeated character in the character stream—Analysis and Code (Java)

Sword refers to offer-50_2. The first non-repeated character in the character stream-analysis and code [Java]

1. Title

Title description
Please implement a function to find the first character that appears only once in the character stream. For example, when the first two characters "go" are read only from the character stream, the first character that appears only once is "g". When reading the first six characters "google" from the character stream, the first character that appears only once is "l".
Output description:
If there is no character that appears once in the current character stream, the # character is returned.

Two, analysis and code

1. Hash table

(1) Thinking

This question can be solved by the same idea as question 50. In the process of inputting the character stream, judge whether the character has appeared and recorded within O(1) time complexity, so that the overall complexity is controlled at O(n).
This idea can be achieved in combination with a hash table, and there are 2 points that can be optimized:
1) The number of letters is limited, and can be directly converted into continuous numbers in combination with its ASCII code, so the hash table can be realized through an array Function;
2) If the number of characters that appear in the hash table is recorded, the position of the character needs to be traversed again, so the position of the character can be directly recorded and the repeated characters can be distinguished, for example, the first The position of the character that appears once is recorded, and the repeated occurrence is recorded as -2, so that the required answer can be obtained in one traversal.

(2) Code

public class Solution {
    
    
    int[] chars = new int[128];
    int index = 1;
    
    //Insert one char from stringstream
    public void Insert(char ch)
    {
    
    
        if (chars[ch] == 0)
            chars[ch] = index++;
        else
            chars[ch] = -1;
    }
  //return the first appearence once char in current stringstream
    public char FirstAppearingOnce()
    {
    
    
        int index = 0;
        char ans = '#';
        for (int i = 0; i < 128; i++)
            if (chars[i] > 0 && (index == 0 || index > chars[i])) {
    
    
                index = chars[i];
                ans = (char)i;
            }
        return ans;
    }
}

(3) Results

Running time: 12 ms, occupied memory: 9552 k.

Three, other

Nothing.

Guess you like

Origin blog.csdn.net/zml66666/article/details/109267028