"Sword Finger Offer"-54. The first non-repeated character in the character stream

1. Knowledge points of this question

Hash table

2. 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 this character stream, the first character that appears only once is "l".

If there is no character that appears once in the current character stream, the # character is returned.

3. Problem solving ideas

  1. Use HashMap to create a mapping between each character and its number of occurrences
  2. Traverse the string in turn, find the first character with 1 occurrence, and return that character
  3. If there is no character that appears once in the current character stream, return the # character

4. Code

public class Solution {
    
    
    String str = "";

    public void Insert(char ch) {
    
    
        str += ch;
    }

    public char FirstAppearingOnce() {
    
    
        // 用 HashMap 建立每个字符与其出现次数的映射
        HashMap<Character, Integer> hashMap = new HashMap<>();
        for (int i = 0; i < str.length(); i++) {
    
    
            char c = str.charAt(i);
            hashMap.put(c, hashMap.getOrDefault(c, 0) + 1);
        }

        // 依次遍历字符串,找到第一个出现次数为 1 的字符,返回该字符
        for (int i = 0; i < str.length(); i++) {
    
    
            char c = str.charAt(i);
            if (hashMap.get(c) == 1) {
    
    
                return c;
            }
        }
        // 如果当前字符流没有存在出现一次的字符,返回 # 字符
        return '#';
    }
}

Guess you like

Origin blog.csdn.net/bm1998/article/details/112962030