题目描述:
请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。
解法1:
class Solution
{
public:
//Insert one char from stringstream
//对于字符串要求不重复,返回第一个不重复的字符串
void Insert(char ch) {
v.push_back(ch);//将元素添加到vector动态数组中,先把元素添加到vector中
}
//return the first appearence once char in current stringstream
char FirstAppearingOnce() {
if(v.empty())return '#';
for(auto &ch:v){//auto可以在声明变量的时候根据变量初始值的类型自动为此变量选择匹配的类型
if(count(v.begin(),v.end(),ch)==1)return ch;//count统计某一值在一定范围内出现的次数
}
return '#';
}
vector<char>v;
};
count函数原型-统计某一值在一定范围内出现的次数
template <class InputIterator, class T>
typename iterator_traits<InputIterator>::difference_type
count (
InputIterator first,
InputIterator last,
const T& val
);
解法2:借助unordered_map
class Solution
{
public:
//Insert one char from stringstream
void Insert(char ch) {//先把每个字符串按照字母插入进去
v.push_back(ch);
unmp[ch]++;
}
//return the first appearence once char in current stringstream
char FirstAppearingOnce() {
for(auto &ch:v){
if(unmp[ch]==1)return ch;
}
return '#';
}
vector<char>v;
unordered_map<char, int>unmp;
};