腾讯笔试题:压缩算法

题目

时间限制:C/C++ 1秒,其他语言2秒空间限制:C/C++ 256M,其他语言512M
小Q想要给他的朋友发送一个神秘字符串,但是他发现字符串的过于长了,
于是小Q发明了一种压缩算法对字符串中重复的部分进行了压缩,
对于字符串中连续的m个相同字符串S将会压缩为[m|S](m为一个整数且1<=m<=100),
例如字符串ABCABCABC将会被压缩为[3|ABC],
现在小Q的同学收到了小Q发送过来的字符串,你能帮助他进行解压缩么? 

示例1

输入
HG[3|B[2|CA]]F

输出
HGBCACABCACABCACAF

说明
HG[3|B[2|CA]]F−>HG[3|BCACA]F−>HGBCACABCACABCACAF

解答

package offer.tengxun;

import java.util.Scanner;
import java.util.Stack;

public class Compress
{
	public static void main(String[] args)
	{
		Scanner in = new Scanner(System.in);
		String line = in.nextLine();
		in.close();
		Stack<String> compress =new Stack<String>();
		for(int x=0;x<line.length();x++)
		{
			if(line.charAt(x)==']')
			{
				String temp ="";
				while(!compress.isEmpty() &&!compress.peek().equals("|"))
				{
					temp = compress.pop()+ temp;
				}
				compress.pop();
				String number= "";
				while(!compress.isEmpty() &&!compress.peek().equals("["))
				{
					number= compress.pop()+number;
				}
				compress.pop();
				Integer count=Integer.parseInt(number);
				String tempString ="";
				for(int y=0;y<count;y++)
				{
					tempString +=temp;
				}
				compress.push(tempString);
			}
			else
			{
				compress.push(line.charAt(x)+"");
			}
		}
		String result="";
		while(!compress.isEmpty())
		{
			result= compress.pop()+result;
		}
		System.out.println(result);
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ReflectMirroring

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值