就是,{}这里面用一个地柜去求解出结果,自定义了一个数据类型
题目:
某位程序想出了一个压缩字符串的方法,压缩后的字符串如下: 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();
}