字符串、map
一 题目
请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。
输出描述:
如果当前字符流没有存在出现一次的字符,返回#字符。
二 思路
创建一个哈希表,每次往字符串里面添加一个字符的时候 ,并用哈希表统计该字符出现的次数,最后遍历哈希表,找到出现次数为1的字符。
C++:
class Solution
{
private:
string s;
map<char, int> items;
public:
//Insert one char from stringstream
void Insert(char ch)
{
s += ch;
items[ch]++;
}
//return the first appearence once char in current stringstream
char FirstAppearingOnce()
{
for(int i=0; i<s.size(); i++){//字符串S的长度就是map元素的个数
if(items[s[i]] == 1){
return s[i];
}
}
return '#';
}
};
python:
# -*- coding:utf-8 -*-
class Solution:
def __init__(self):
self.s = ''
self.hashmap = {}
# 返回对应char
def FirstAppearingOnce(self):
length = len(self.s)
for i in range(length):
if self.hashmap[self.s[i]] == 1:
return self.s[i]
return '#'
def Insert(self, char):
self.s += char
if char not in self.hashmap:
self.hashmap[char] = 1
else:
self.hashmap[char] += 1