带你快速刷完67道剑指offer
如果你想在校招中顺利拿到更好的offer,阿秀建议你多看看前人的经验 ,比如准备 、简历 、实习 、校招总结 、offer选择 、也欢迎来一起参加秋招打卡活动 等;如果你是计算机小白,学习/转行/校招路上感到迷茫或者需要帮助,可以点此联系阿秀;免费分享阿秀个人学习计算机以来的收集到的好资源,点此白嫖;如果你需要《阿秀的学习笔记》网站中求职相关知识点的PDF版本的话,可以点此下载
# No54、字符流中第一个不重复的字符
# 题目描述
请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。
如果当前字符流没有存在出现一次的字符,返回#字符。
1
# 1、自己想的一种方法
class Solution
{
public:
//Insert one char from stringstream
void Insert(char ch)
{
v.push_back(ch);
}
//return the first appearence once char in current stringstream
char FirstAppearingOnce()
{
if(v.empty()) return '#';
/*int len = v.size();*/
for (auto &ch:v) {
if (count(v.begin(), v.end(), ch) == 1) return ch;
}
return '#';
}
vector<char> v;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 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;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 二刷:
# 1、简单的方法,复杂度稍微高一些
运行时间:4ms 占用内存:376k
class Solution
{
public:
//Insert one char from stringstream
void Insert(char ch)
{
v.push_back(ch);
}
//return the first appearence once char in current stringstream
char FirstAppearingOnce()
{
for (auto &ch:v) {
if (count(v.begin(),v.end(),ch) == 1) return ch;
}
return '#';
}
vector<char> v;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 2、借助一个哈希表,稍微快一点了
运行时间:4ms 占用内存:376k
class Solution
{
public:
//Insert one char from stringstream
void Insert(char ch)
{
v.push_back(ch);
result[ch]++;
}
//return the first appearence once char in current stringstream
char FirstAppearingOnce()
{
for (auto &ch:v) {
if (result[ch] == 1) return ch;
}
return '#';
}
vector<char> v;
unordered_map<char,int> result;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22