【 声明:版权所有,转载请标明出处,请勿用于商业用途。 联系信箱:libin493073668@sina.com】
题目描述
请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。
输出描述:
如果当前字符流没有存在出现一次的字符,返回#字符。
思路
我们使用哈希表来标记各个字符对应的状态
-1:表示没有出现过
-2:表示出现过多次
0~n:表示出现的位置
然后我们再一遍循环找到位置最小的即可
class Solution
{
public:
//Insert one char from stringstream
Solution():index(0)
{
for(int i = 0; i<256; ++i)
state[i] = -1;
}
void Insert(char ch)
{
if(state[ch]==-1)
state[ch] = index;
else if(state[ch]>=0)
state[ch] = -2;
++index;
}
//return the first appearence once char in current stringstream
char FirstAppearingOnce()
{
char ch = '#';
int minIndex = index;
for(int i = 0; i<256; ++i)
{
if(state[i]>=0 && state[i]<minIndex)
{
minIndex = state[i];
ch = (char)i;
}
}
return ch;
}
private:
int state[256];
int index;
};