(Java refers to offer) The first non-repeated character in the character stream

1. Question analysis

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

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

If you don’t look at the core code on Niuke in this question, my first thought is to use the string to get the first and last index to determine whether a character appears only once ( string.indexOf()和string.lastIndexOf()), But the core code given is:

Insert picture description here
This is not easy to operate. Here you need to insert a string first, and then find the first character that only appears once:
It can be seen that this is actually a correspondence, a key-value correspondence, so it can be used linkedHashMap(disordered storage, keys are not allowed to be repeated)

Second, the code

import java.util.LinkedHashMap;
import java.util.Map;
public class Solution {
    
    
     //map 用来记录每个字符出现的次数
    Map<Character, Integer> linkedHashMap = new LinkedHashMap<>();
    //Insert one char from stringstream
    public void Insert(char ch)
    {
    
    
        //如果字符 ch 已经存储,则存储次数加 1,否则存储一次
        if (linkedHashMap.containsKey(ch)) {
    
    
            linkedHashMap.put(ch, linkedHashMap.get(ch) + 1);
        } else {
    
    
            linkedHashMap.put(ch, 1);
        }
    }
  //return the first appearence once char in current stringstream
    public char FirstAppearingOnce()
    {
    
    
    //如果当前字符流没有存在出现一次的字符,返回#字符。
    char ch = '#';
        for (Map.Entry<Character, Integer> map : linkedHashMap.entrySet()) {
    
    
            if (map.getValue() == 1) {
    
    
                ch = map.getKey();
                break;
            }
        }
        return ch;
    }
}

Three, summary

(1)LinkedHashMap It is stored in an orderly manner, the reading order is the same as the storage order
(2) For the iterative output of the map set: you can use foreach to output:

for (Map.Entry<Character, Integer> map : linkedHashMap.entrySet()) {
    
    
            if (map.getValue() == 1) {
    
    
                ch = map.getKey();
                break;
            }
        }

Other output methods can refer to: Map interface learning

Guess you like

Origin blog.csdn.net/nanhuaibeian/article/details/108563619