剑指54.字符流中第一个不重复的字符

题目描述

请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。
 

输出描述:

如果当前字符流没有存在出现一次的字符,返回#字符。
 

思路

思路1:使用HashMap+StringBuilder

 

思路2:直接使用LinkedHashMap(有序的)。注意:LinkedHash的有序性是指插入的顺序,TreeMap的有序性是自动按值排序

 

思路3:使用数组实现一个简单的Map

 

解法1

import java.util.*;
public class Solution {
    private Map<Character,Integer> map = new HashMap<>();
    private StringBuilder sb = new StringBuilder();
    //Insert one char from stringstream
    public void Insert(char ch) {
        sb.append(ch);
        map.put(ch,map.getOrDefault(ch,0) + 1);
    }
    //return the first appearence once char in current stringstream
    public char FirstAppearingOnce() {
        int index = 0;
        while (index < sb.length()){
            if (map.get(sb.charAt(index)) == 1){
                return sb.charAt(index);
            }
            index++;
        }
        return '#';
    }
}

 

解法2

import java.util.*;
public class Solution {
    Map<Character,Integer> map = new LinkedHashMap<>();
    //Insert one char from stringstream
    public void Insert(char ch) {
        map.put(ch,map.getOrDefault(ch,0) + 1);
    }
    //return the first appearence once char in current stringstream
    public char FirstAppearingOnce() {
        for (char c : map.keySet()){
            if (map.get(c) == 1)
                return c;
        }
        return '#';
    }
}

 

解法3

Mark

 

 
 
posted @ 2020-09-04 10:37  不学无墅_NKer  阅读(187)  评论(0编辑  收藏  举报