我想编写一个程序来打印重复的字母。我这里有代码,但它会为我打印整个单词。你能给我一些建议吗?
#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;
}
最佳答案
for(int i = 0; i <= word.length(); i++){
应该是i < word.length()
(超出范围)for(int j = 1; j < word.length(); j++){
使用for(int j = i + 1; ...
会更好我猜。
此外,temp
和 temp2
足够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/