今日碎碎念: 回去咯!!
题目描述
请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。
解题分析
c++标准库有unordered_map和map,注意前者是无序的,后者会自动的排序。
用一个str存住所有的字符串,这样才知道谁是第一个出现的,跟前面某一题很像,不然就会返回ascll码小的出现一次的!
代码实现
// 字符的特殊性 256即可搞定
class Solution
{
private:
string str = "";
int mp[256];
public:
//mp初始化
Solution()
{
memset(mp,0,sizeof(mp));
}
//Insert one char from stringstream
void Insert(char ch)
{
str+=ch;
mp[ch]++;
}
//return the first appearence once char in current stringstream
char FirstAppearingOnce()
{
for(int i=0; i<str.size(); i++)
if(mp[str[i]] == 1) return str[i];
return '#';
}
};
结果