这个题目的话其实是可以想到利用一个128大小数组来保存字符出现的次数,只是如果我们要找第一个时,每次都需要从头开始遍历,直到找到一个次数为1的则立即返回。那么我们可不可以简化这个遍历的过程?当我们遇到一个字符时,如果是第一次出现我们就将它放到一个队列中,如果不是第一次就不放到队列中了。当取第一个出现次数为1的字符时,我们去队列里拿,当然随着字符流的进行,队列里的字符不都是只出现一次了,那么我们就从队列里面去找符合条件的。
import java.util.Queue;
import java.util.LinkedList;
public class Solution {
//使用一个int数组来作为哈希?
//Insert one char from stringstream
private int[] flag = new int[128];
Queue<Character> queue = new LinkedList<>();
public void Insert(char ch)
{
if(flag[ch]++ == 0) //如果是第一次出现,则将此字符放到队列中
queue.offer(ch);
}
//return the first appearence once char in current stringstream
public char FirstAppearingOnce()
{
while(!queue.isEmpty() && flag[queue.peek()] != 1) { //找到一个出现次数为1的字符
queue.poll();
}
if(queue.isEmpty()) //如果都不满足返回'#',否则返回队头元素
return '#';
return queue.peek();
}
}