C++ 字符串压缩算法实现 - 压缩连续相同字母
你可以使用以下的 C++ 代码来实现字符串压缩的功能:
#include <iostream>
#include <string>
std::string compressString(const std::string& input) {
std::string compressed;
int count = 1;
for (int i = 1; i <= input.length(); i++) {
if (i == input.length() || input[i] != input[i-1]) {
compressed += std::to_string(count) + input[i-1];
count = 1;
} else {
count++;
}
}
return compressed;
}
int main() {
std::string input;
std::cout << "请输入字符串:";
std::cin >> input;
std::string compressed = compressString(input);
std::cout << "压缩后的字符串为:" << compressed << std::endl;
return 0;
}
这段代码定义了一个 compressString 函数来实现字符串压缩的逻辑。在主函数 main 中,用户输入一个字符串,然后调用 compressString 函数进行压缩,并将结果输出。
运行程序后,你可以输入字符串 aaabbbbbx,然后得到输出结果 3a5bx,与题目要求的输出样例一致。
原文地址: https://www.cveoy.top/t/topic/qcN4 著作权归作者所有。请勿转载和采集!