某易 压缩字符串(这个题好到不得了,对于计算表达式都可以这么做)

就是,{}这里面用一个地柜去求解出结果,自定义了一个数据类型
题目:

某位程序想出了一个压缩字符串的方法,压缩后的字符串如下: 3{a}2{bc},3{a2{c}}2{abc}3{cd}ef,现在需要你写一个解压的程序,还原原始的字符串。如: s = “3{d}2{bc}”, return"dddbcbc".s=“3{a2{d}}”,return"addaddadd".s=“2{efg}3{cd}ef”,return"efgefgcdcdcdef". 重复次数可以确保是一个正整数。
package orc.shi.s;

public class isB {
	public static class data
	{
		int index;
		String str;
		public data(int index,String str){
			this.index=index;
			this.str=str;
		}
	}
	public static void main(String[] args) {
		String test1 = "3{a}2{bc}";
		String test2 = "3{a2{c}}";
		String test3 = "11{abc}3{cd}ef";
		System.out.println(process(0,test3.toCharArray()).str);
	}
	public static data process(int index,char[] chs) {
		String res="";
		int times=0;
		while(index<chs.length&&chs[index]!='}') {
			if(chs[index]=='{') {
				data da=process(index+1,chs);
				while(times>0) {
					res+=da.str;
					times--;
					
				}
				times=0;
				index=da.index+1;
			}else {
				if(chs[index]>='0'&&chs[index]<='9') {
					times=times*10+(int)chs[index]-'0';
				}else 
				{
					res+=chs[index];
				}
				index++;
			}
		}
		return new data(index,res);
	}
}
public static ReturnData process(char[] chs, int index) {
		StringBuilder res = new StringBuilder();
		int times = 0;
		while (index < chs.length && chs[index] != '}') {
			if (chs[index] == '{') {
				ReturnData returnData = process(chs, index + 1);
				res.append(getTimesString(times, returnData.str));
				times = 0;
				index = returnData.end + 1;
			} else {
				if (chs[index] >= '0' && chs[index] <= '9') {
					times = times * 10 + chs[index] - '0';
				}
				if (chs[index] >= 'a' && chs[index] <= 'z') {
					res.append(String.valueOf(chs[index]));
				}
				index++;
			}
		}
		return new ReturnData(res.toString(), index);
	}

	public static String getTimesString(int times, String base) {
		StringBuilder res = new StringBuilder();
		for (int i = 0; i < times; i++) {
			res.append(base);
		}
		return res.toString();
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值