题解 | #字符流中第一个不重复的字符#
字符流中第一个不重复的字符
http://www.nowcoder.com/practice/00de97733b8e4f97a3fb5c680ee10720
import java.util.*;
public class Solution {
//Insert one char from stringstream
//HashMap判断是否重复
//队列Que给出第一个不重复的字符
static HashMap<Character, Boolean> map = new HashMap<Character, Boolean>();
static Queue<Character> que = new LinkedList<Character>();
public void Insert(char ch)
{
//判断是否重复
//重复,则char键对应的boolean值为false,否则为true
if(map.containsKey(ch)){
map.put(ch, false);
}else {
map.put(ch, true);
que.offer(ch);
}
}
//return the first appearence once char in current stringstream
public char FirstAppearingOnce()
{
while(!que.isEmpty()){
//非空且que.peek()对应的值为false,poll
if(map.get(que.peek()).equals(false)){
que.poll();
continue;
}
//非空且que.peek()对应的值为true,返回peek()
return (char)que.peek();
}
//队列为空,不存在不重复的数字,返回"#"
return '#';
}
}