Skip to content

Commit 6599da2

Browse files
authored
Create 7.3.1找到第一个不重复的字符.md
1 parent f75fc60 commit 6599da2

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
- 问题:编写一个高效的函数来查找字符串中的第一个非重复字符并讨论算法的效率。
2+
- 例子:total—输出’o’
3+
- 例子:teeter—输出’r’
4+
- 思想:使用一个map存储每个字符出现的次数,接着重新遍历一遍字符串,找到第一个出现次数为1的字符并返回。
5+
6+
```
7+
#include <iostream>
8+
#include <map>
9+
#include <string>
10+
11+
char GetUniqueChar(const std::string& str){
12+
std::map<char, int> memo;
13+
for(int i = 0; i < str.size(); i++){
14+
memo[str[i]]++;
15+
}
16+
17+
for(int i = 0; i < str.size(); i++){
18+
if(memo[str[i]] == 1){
19+
return str[i];
20+
}
21+
}
22+
return '\0';
23+
}
24+
25+
int main() {
26+
std::string input1 = "iwillcometowatchthephantomoftheopera";
27+
std::string input2 = "withmybfonoctobor5,2023";
28+
char uniqueChar1 = GetUniqueChar(input1);
29+
char uniqueChar2 = GetUniqueChar(input2);
30+
31+
if (uniqueChar1 != '\0') {
32+
std::cout << "The first unique character is: " << uniqueChar1 << std::endl;
33+
} else {
34+
std::cout << "No unique character found." << std::endl;
35+
}
36+
if (uniqueChar2 != '\0') {
37+
std::cout << "The first unique character is: " << uniqueChar2 << std::endl;
38+
} else {
39+
std::cout << "No unique character found." << std::endl;
40+
}
41+
42+
return 0;
43+
}
44+
```

0 commit comments

Comments
 (0)