1078 字符串压缩与解压

本文分享了字符串压缩与解压的C++实现代码,详细介绍了如何使用make_pair进行数据结构构建,通过压缩算法减少存储空间,以及解压算法还原原始数据。适合初学者理解并实践字符串处理的基本技巧。

1078 字符串压缩与解压

解题代码

#include<iostream>
#include<string>
#include<vector>
#include<cctype>
using namespace std;
vector<pair<char, int>> v;
void compress(string str) {
	int len = str.length();
	for (int i = 0; i < len; i++) {
		if (!i || str[i] != str[i - 1]) {
			v.push_back(make_pair(str[i],1));
		}
		else v.back().second++;
	}
	for (auto x : v) {
		if (x.second != 1) cout << x.second;
		cout << x.first;
	}
}
void decompress(string str) {
	int len = str.length();
	for (int i = 0; i < len; i++) {
		if (isalpha(str[i]) || str[i] == ' ') cout << str[i];
		else {
			int pos = i;
			while (isdigit(str[pos++])) {};
			pos -= 2;
			int cnt = stoi(str.substr(i, pos - i + 1));
			for (int j = 0; j < cnt; j++) cout << str[pos + 1];
			i = pos + 1;
		}
	}
}
int main() {
	char c;
	string str;
	cin >> c;
	getchar();
	getline(cin, str);
	if (c == 'C') compress(str);
	else decompress(str);
	return 0;
}

测试结果

在这里插入图片描述

问题整理

1.基础题目。
2.明白了make_pair()的用法,等同于<>。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值