版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ccnuacmhdu/article/details/84889001
时间限制:1秒 空间限制:32768K 热度指数:91819
本题知识点: 字符串
题目描述
请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。
输出描述:
如果当前字符流没有存在出现一次的字符,返回#字符。
注意
要用LinkedHashMap,确保按照顺序进入map,然后找到当前第一个出现一次的字符
import java.util.*;
public class Solution {
//Insert one char from stringstream
private LinkedHashMap<Character, Integer> map = new LinkedHashMap<Character, Integer>();
public void Insert(char ch)
{
if(map.containsKey(ch)){
map.put(ch, map.get(ch)+1);
}else{
map.put(ch, 1);
}
}
//return the first appearence once char in current stringstream
public char FirstAppearingOnce()
{
Iterator it = map.entrySet().iterator();
while(it.hasNext()){
Map.Entry entry = (Map.Entry)it.next();
Character key = (Character)entry.getKey();
Integer value = (Integer)entry.getValue();
if(value == 1){
return key;
}
}
return '#';
}
}