字符流中第一个不重复的字符

问题描述

请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符”go”时,第一个只出现一次的字符是”g”。当从该字符流中读出前六个字符“google”时,第一个只出现一次的字符是”l”。
如果当前字符流没有存在出现一次的字符,返回#字符。

思路分析

核心思想就是创建一个map用来记录每个字符出现的次数,而list则记录只出现一次的字符集合,遍历字符,如果map中不存在说明是第一次,则把字符作为key加入,然后在放到list中,如果map中包含了该键,一方面记录该字符次数,另一方面看list中是否包含该元素,在删除,最后list中只保留出现一次的字符

码上有戏

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Solution {
private Map<Character, Integer> map=new HashMap<Character, Integer>();
private List<Character> list=new ArrayList<Character>();
//Insert one char from stringstream
public void Insert(char ch)
{
if(!map.containsKey(ch)){
map.put(ch, 1);
list.add(ch);
}else{
map.put(ch, map.get(ch)+1);
if(list.contains(ch))
list.remove(Character.valueOf(ch));
}
}
//return the first appearence once char in current stringstream
public char FirstAppearingOnce()
{
if(list.isEmpty())return '#';
return list.get(0);
}
}

热评文章