简单的解压缩算法 c++
时间: 2023-06-14 08:05:07 浏览: 61
下面是一个简单的解压缩算法 C++ 的示例代码,可以解压由连续的重复字符和重复次数构成的字符串:
```c++
#include <iostream>
#include <string>
using namespace std;
string decompress(string compressed) {
string decompressed = "";
int i = 0;
while (i < compressed.length()) {
int repeat = compressed[i+1] - '0'; // 获取重复次数
for (int j = 0; j < repeat; j++) {
decompressed += compressed[i];
}
i += 2; // 跳过已处理的字符和重复次数
}
return decompressed;
}
int main() {
string compressed = "a3b2c4";
string decompressed = decompress(compressed);
cout << "Compressed string: " << compressed << endl;
cout << "Decompressed string: " << decompressed << endl;
return 0;
}
```
该算法的基本思路是遍历压缩字符串中的每个字符,如果遇到字母,则获取它后面的数字重复次数,并将该字母重复指定次数添加到解压缩后的字符串中。
相关推荐
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)