字符流中第一个不重复的字符
- 请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。
- 利用数组来组建一个map
- key为字符,value为出现的顺序
- 默认map的初始值为0,表示为未出现
- 维护一个index,字符第一次出现设置为当前的index,index自增;若多次出现,则设置为-1,表示不可能。
- get时只需要取得index最小并与之对应的字符
- C++ 代码
import java.util.*;
public class Solution {
int[] count = new int[256];
int index = 1;
//Insert one char from stringstream
public void Insert(char ch)
{
if(count[ch] == 0){
count[ch] = index++;
}else{
count[ch] = -1;
}
}
//return the first appearence once char in current stringstream
public char FirstAppearingOnce()
{
char res = '#';
int tmp = Integer.MAX_VALUE;
for(int i= 0; i<256; i++){
if(count[i]!=-1 && count[i]!=0 && count[i]<tmp){
tmp = count[i];
res = (char)i;
}
}
return res;
}
}
本文标题:字符流中第一个不重复的字符
本文链接:https://www.haomeiwen.com/subject/gkkjlktx.html
网友评论