1. 程式人生 > 實用技巧 >劍指54.字元流中第一個不重複的字元

劍指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