Skip to content

Latest commit

 

History

History
44 lines (38 loc) · 1.29 KB

7.3.1找到第一个不重复的字符.md

File metadata and controls

44 lines (38 loc) · 1.29 KB
  • 问题:编写一个高效的函数来查找字符串中的第一个非重复字符并讨论算法的效率。
    • 例子:total—输出’o’
    • 例子:teeter—输出’r’
    • 思想:使用一个map存储每个字符出现的次数,接着重新遍历一遍字符串,找到第一个出现次数为1的字符并返回。
#include <iostream>
#include <map>
#include <string>

char GetUniqueChar(const std::string& str){
    std::map<char, int> memo;
    for(int i = 0; i < str.size(); i++){
        memo[str[i]]++;
    }

    for(int i = 0; i < str.size(); i++){
        if(memo[str[i]] == 1){
            return str[i];
        }
    }
    return '\0';
}

int main() {
    std::string input1 = "iwillcometowatchthephantomoftheopera";
    std::string input2 = "withmybfonoctobor5,2023";
    char uniqueChar1 = GetUniqueChar(input1);
    char uniqueChar2 = GetUniqueChar(input2);

    if (uniqueChar1 != '\0') {
        std::cout << "The first unique character is: " << uniqueChar1 << std::endl;
    } else {
        std::cout << "No unique character found." << std::endl;
    }
    if (uniqueChar2 != '\0') {
        std::cout << "The first unique character is: " << uniqueChar2 << std::endl;
    } else {
        std::cout << "No unique character found." << std::endl;
    }

    return 0;
}