题目

时间限制: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);
}
}