//思路一:暴力解法
//先将所有数据插入,再进行统计
private StringBuffer buffer=new StringBuffer();
//Insert one char from stringstream
public void Insert(char ch)
{
buffer.append(ch);
}
//return the first appearence once char in current stringstream
public char FirstAppearingOnce(){
int[] freq = new int[256];
for(int i=0;i<buffer.length();i++){
char ch = buffer.charAt(i);
freq[ch]++;
}
for(int i=0;i<buffer.length();i++){
char ch = buffer.charAt(i);
if(freq[ch]==1){
return ch;
}
}
return '#';
}
//思路二:
//利用队列先进先出的特性
//统计字符出现的次数
private int[] freq = new int[256];
//队列中值存储出现一次的字符,并且出队顺序就是入队顺序一致
private Queue<Character> queue = new LinkedList<>();
//Insert one char from stringstream
public void Insert(char ch) {
freq[ch]++;
queue.offer(ch);
while (!queue.isEmpty() && freq[queue.peek()]>1){
queue.poll();
}
}
//return the first appearence once char in current stringstream
public char FirstAppearingOnce(){
return queue.isEmpty()? '#':queue.peek();
}
https://www.mianshi.online,https://www.i9code.cn
本文由博客一文多发平台 OpenWrite 发布!
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。