File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed
Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change 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+ ```
You can’t perform that action at this time.
0 commit comments