2020腾讯秋招笔试编程题--压缩算法

题目描述

对于字符串中连续的M个相同字符串S将会压缩为[M|S](M为一个整数且1<=M<=100),例如字符串ABCABCABC将会压缩为[3|ABC],现在接收一段字符串,对其进行解压缩。

输入描述:

输入第一行包含一个字符串s,代表压缩后的字符串。

s的长度<=1000;

s仅包含大写字母、[、|、];

解压后的字符串长度不超过100000;

输出描述

输出一个字符串,代表解压后的字符串。

示例:输入HG[3|B[2|CA]]F

输出HGBCACABCACABCACAF

解题思路:

从右往左搜索,记录右中括号次数,查找与右括号次数相同的左括号为一个大的重复。使用堆栈进行操作,数组进行保存。

代码

#include "stdafx.h"
#include <iostream>
#include <string>
#include<stack>
#include<vector>
using namespace std;


int main()
{
	string temp;
	cin>>temp;
	stack<char> save;
	for (int i = 0; i < temp.size(); i++)
	{
		save.push(temp[i]);
	}
	vector<char> result;
	vector<vector<char>> save_result;
	while (!save.empty())
	{
		int count = 0; 
		if (save.top()>='A' && save.top()<='Z')
		{
			result.insert(result.begin(), save.top());
			save.pop();
		}
		else if (save.top() == ']')
		{
			count++;
			save.pop();
		}
		while (count)
		{
			int no = 0, cnt = 0;
			if (save.top() == '|')
			{

				save.pop();
				while (save.top() >= '0'&& save.top() <= '9')
				{
					char s1 = save.top();
					no += pow(10, cnt)*(int)(s1-'0');
					cnt++;
					save.pop();
				}
				int size = result.size();
				no--;
				while (no)
				{
					for (int i = 0; i < size; i++) result.push_back(result[i]);
					no--;
				}
				no = 0, cnt = 0;
			}
			else if (save.top() == ']')
			{
				count++;
				save.pop();
			}
			else if (save.top() == '[')
			{
				count--;
				save.pop();
			}
			else
			{
				result.insert(result.begin(),save.top());
				save.pop();
			}
		}
		save_result.insert(save_result.begin(),result);
		result.clear();
	}
	for (int i = 0; i < save_result.size(); i++)
	{
		for (int j = 0; j < save_result[i].size(); j++) cout << save_result[i][j];
	}
	return 0;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值