腾讯2020校招题-赛码网
方法一:
从键盘键入后,取得字符串;遍历字符串,存入StringBuider,直到获得第一个']';
获得第一个']'之后,往前读取得到重复次数,然后把目标子串重复后的结果添加到StringBuider中
继续往后存字符串,重复上面的过程
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
String str = in.nextLine();
System.out.println(uncompress(str));
}
private static String uncompress(String str){
StringBuilder res = new StringBuilder();// 结果记录
for(int i=0; i<str.length(); i++){
char ch = str.charAt(i);
if(ch!=']'){ // [ num | targetStr ]
res.append(ch);
}else{ //ch==']'
String times;
int endIndex = res.length()-1;
int j = endIndex;//从endIndex往前倒,去找到数字和startIndex
StringBuilder targetStr = new StringBuilder();//重复的目标子串
while(res.charAt(j)!='['){
if(res.charAt(j)=='|'){
targetStr.append(res.substring(j+1));
endIndex = j;//数字字符串尾
}
j--;
}
times = res.substring(j+1,endIndex);//记录重复的次数
int time = Integer.parseInt(times);
StringBuilder uncompressStr = new StringBuilder();
for(int t=0; t<time; t++){
uncompressStr.append(targetStr);
}
StringBuilder temp = new StringBuilder();
res = temp.append(res.substring(0,j)).append(uncompressStr);
}
}
return res.toString();
}
}
方法二:参考自灰信网编程题 - 灰信网(软件开发博客聚合)
import java.util.Collections;
import java.util.Scanner;
public class Main {
private static String getstr(String words){
while (words.contains("]")){
int right = words.indexOf("]");
int left = words.lastIndexOf("[",right);
String repeatStr = words.substring(left + 1, right);
String[] split = repeatStr.split("\\|"); //字符串拆分成数组
words = words.replace("[" + repeatStr+"]",
String.join("", Collections.nCopies(Integer.parseInt(split[0]), split[1])));//把[***]替换成split[0]次重复的split[1]
}
return words;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String str = in.nextLine();
System.out.println(getstr(str));
}
}