题目描述
请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。
输出描述:
如果当前字符流没有存在出现一次的字符,返回#字符。
解题思路
insert函数接收字符;FirstAppearingOnce函数找到不重复的第一个字符。可以很简单的实现,往往网上的代码却很复杂。
代码实现
class Solution
{
public:
//Insert one char from stringstream
string str;
void Insert(char ch)
{
str.push_back(ch);
}
//return the first appearence once char in current stringstream
char FirstAppearingOnce()
{
if (str.size() == 0)
return '\0';
string::iterator iter = str.begin();
for (; iter != str.end(); iter++)
if (count(str.begin(), str.end(), *iter) == 1)
return *iter;
return '#';
}
};
本文介绍如何使用C++编程找出字符流中第一个只出现一次的字符。通过insert函数添加字符到流,FirstAppearingOnce函数查找不重复的字符。解题思路简洁,不同于网上复杂的实现。
4850

被折叠的 条评论
为什么被折叠?



