思路:建立哈希表统计每个字符出现的次数即可
class Solution
{
public:
string s;//储存当前的字符流
int hashtable[256];
Solution ()//用构造函数初始化
{
s = "";
for(int i = 0; i < 256; i++)
hashtable[i] = 0;
}
//Insert one char from stringstream
void Insert(char ch)
{
hashtable[ch]++;
s += ch;//拼接当前的字符串
}
//return the first appearence once char in current stringstream
char FirstAppearingOnce()
{
int len = s.size();
for(int i = 0; i < len ;i++)//找到字符串中第一个不重复出现的字符
{
if(hashtable[s[i]] == 1)
return s[i];
}
return '#';
}
};
Python 实现
class Solution:
# 返回对应char
def __init__(self):
self.res = []
def FirstAppearingOnce(self):
if not self.res:
return '#'
return self.res[0]
def Insert(self, char):
if char in self.res:
self.res.remove(char)##重复的就移走
else:
self.res.append(char)##不重复的就加入列表