描述
请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。
后台会用以下方式调用Insert 和 FirstAppearingOnce 函数
string caseout = “”;
1.读入测试用例字符串casein
2.如果对应语言有Insert()函数的话,执行Insert() 函数
3.循环遍历字符串里的每一个字符 ch { Insert(ch); caseout += FirstAppearingOnce() }
4.输出caseout,进行比较。
返回值
如果当前字符流没有存在出现一次的字符,返回#字符。
解题
import java.util.LinkedList;
import java.util.Queue;
public class Solution {
//Insert one char from stringstream
Queue<Character> queue = new LinkedList<>();
int[] arr = new int[128];
public void Insert(char ch)
{
queue.add(ch);
arr[ch]++;
while (!queue.isEmpty() && arr[queue.peek()] > 1)
queue.poll();
}
public char FirstAppearingOnce()
{
return queue.isEmpty() ? '#' : queue.peek();
}
}