c++ - 在 C++ 中打印重复的字母

标签 c++ string for-loop

我想编写一个程序来打印重复的字母。我这里有代码,但它会为我打印整个单词。你能给我一些建议吗?

#include <iostream>

using namespace std;
int main(){
string slowo, temp, temp2;

cout << "Insert word: ";
cin >> word;

for(int i = 0; i <= word.length(); i++){
    temp = word[i];

    for(int j = 1; j < word.length(); j++){
        temp2 = word[j];

        if(temp == temp2)
            cout << temp2;
    }
}
return 0;
}

最佳答案

  1. for(int i = 0; i <= word.length(); i++){
    应该是 i < word.length() (超出范围)

  2. for(int j = 1; j < word.length(); j++){
    使用 for(int j = i + 1; ... 会更好我猜。

此外,temptemp2足够char (您正在构建不必要的新字符串)。

但是请注意,如果字母重复不止一次,则此解决方案或已接受的解决方案将多次输出字母。例如。 “reparature”这个词将输出字母“r”三次。如果您只需要输出每个重复的字母一次,则需要跟踪您已经写出的字母,例如通过 std::map(或 C++11 的 unordered_map)。

此外,您实际上可以在 O(n)(使用 std::unordered_map)或 O(n * log n)(使用 std::map)而不是 O(n^2)(当前解决方案)。

这里是如何在 O(n) 中做到这一点(摊销):

unordered_map<char, int> mem;
for (int i = 0; i < word.length(); i++){
    const char c = word[i];
    if (mem[c]++ == 1)
       cout << c;
}

关于c++ - 在 C++ 中打印重复的字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36498838/

相关文章:

C++ 如何替换代码中不寻常的引号

c++ - MongoDB c++ 遗留驱动程序 1.1.2 不工作 - 使用 VS2013、Win 10、boost-1_62 编译

文件 FileReader 的 JavaScript for 循环

c - 为什么这个 C for 循环不能正常工作?

C++20 协程、std 返回类型和状态持久性

c++ - 如何实现梯度高斯模糊?

java - 转换网址

mysql字符串到IN子句分割字符串之类的?

java - 从字符串中获取字节

java - 在流中存储新实例