题解 | #字符流中第一个不重复的字符#
字符流中第一个不重复的字符
http://www.nowcoder.com/practice/00de97733b8e4f97a3fb5c680ee10720
import java.util.*;
public class Solution {
//Insert one char from stringstream
//思路:
// 插入时:
// 建一个map,用来存放每个字符出现的次数。建一个队列Queue用来按顺序存放每个字符
//有一个条件是,当一个字符之前已经出现过,则对map中这个字符的个数加1。同时,对于队列因为已经存在了
//故不需要添加这个字符。
// 取出时:
// 查看队列头的元素。在map中对比它的次数是否为1.如果为1,则直接返回这个字符。
//否则弹出队列头元素,继续下一个判断。
// 直到队列为空
HashMap<Character,Integer> map = new HashMap<>();
Queue<Character> queue = new LinkedList<>();
public void Insert(char ch)
{
if(!map.containsKey(ch)){
queue.offer(ch);
map.put(ch,1);
}else{
int num = map.get(ch)+1;
map.put(ch,num);
}
}
//return the first appearence once char in current stringstream
public char FirstAppearingOnce()
{
while(!queue.isEmpty()){
char head = queue.peek();
if(map.get(head)==1){
return head;
}else{
queue.poll();
continue;
}
}
return '#';
}
}
查看19道真题和解析
上海得物信息集团有限公司公司福利 1166人发布