C ++中的第一个重复出现的字符

时间:2018-11-23 21:01:07

标签: c++

我仅在Python和JS中找到了此问题的一些答案,希望您可以帮助我在c ++中执行相同的操作。 因此,挑战在于打印给定字符串的第一个重复出现的字符,这是我想出的,但是我不知道这段代码是否看起来不错。这是我第一次在StackOverflow上发帖,希望我能得到一些反馈=)

#include <iostream>
#include <vector>

int main() {
    std::cout << "Enter some letters:\n";
    std::string str;
    std::cin >> str;

    // vector that stores characters that we will come across in the string
    std::vector<char> seen(0);

    for (char a : str) {
        for (int i = 0; i < seen.size(); i++) {
            if (a == seen[i]) {
                std::cout << a << std::endl;
                return 0;
            } else { continue; }
        }
        seen.push_back(a);
    }
    std::cout << "none\n";
    return 0;
}

3 个答案:

答案 0 :(得分:1)

对于您的任务,请查看std::find

void printRecurring(const std::string& str) {
  std::string::const_iterator it = str.begin(), e = str.end();

  for (std::string::const_iterator it2 = str.begin(); it2 != str.end(); ++it2) {
    it = std::find(it + 1, e, *it2);
    if (it != str.end()) {
        std::cout << *it2 << std::endl;
        return;
    }
  }
}

答案 1 :(得分:1)

关于速度,如何:

#include <iostream>

int main() {
    std::cout << "Enter some letters:\n";
    std::string str;
    std::cin >> str;

    bool seen [256] = { };

    for (char a : str) {
        unsigned char u = (unsigned char) a;
        if (seen [u]) {
            std::cout << a << std::endl;
            return 0;
        }
        seen [u] = true;
    }
    std::cout << "none\n";
    return 0;
}

这是O(N),而不是O(N * N / 2)

Live demo

答案 2 :(得分:0)

我认为您可以使用std :: find使其变得更简单。

#include <iostream>
#include <vector>
#include <algoritm>

int main()
{
    std::cout << "Enter some letters:\n";
    std::string str;
    std::cin >> str;

    // vector that stores characters that we will come across in the string
    std::vector<char> seen(0);


    for (char a : str) {
        auto it = std::find(seen.begin(), seen.end(), a);
        if (it != seen.end()) {
            std::cout << "Found it: " << *it << std::endl;
            return 0;
        }
        seen.push_back(a);

    }

std::cout << "none\n";
return 0;
}