我的答案:思路很明显,就是用栈去模拟这个过程。
import java.util.*;
public class Main {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
while(scanner.hasNextLine()){
int n = scanner.nextInt();
scanner.nextLine();
for (int i = 0; i < n; i++) {
char[] chars = scanner.nextLine().toCharArray();
Stack<Character> stack = new Stack<>();
int index = 0;
StringBuilder result = new StringBuilder();
while(index < chars.length){
//如果是'('或字母直接入栈
if(chars[index] == '(' || (chars[index] >= 'A' && chars[index] <= 'Z')) {
stack.push(chars[index++]);
}
//‘)’后面一定是数字
//如果是')'则找到后面的连续数字表示多少倍,然后出栈直到遇到'(',将字符多少倍的入栈
else if(chars[index] == ')'){
index++;
//找出后面的数字时多少
int num = 0; //括号后面的数字
while (index < chars.length && Character.isDigit(chars[index])){
num = num*10 + chars[index] - '0';
index++;
}
//找到栈中的'('将字符串乘以num倍
ArrayList<Character> tmp = new ArrayList<>();
while (!stack.isEmpty() && stack.peek()!='('){
tmp.add(stack.pop());
}
stack.pop();
for (int j = 0; j < num; j++) {
for (int k = tmp.size()-1; k >= 0; k--) {
stack.add(tmp.get(k));
}
}
}
//如果是数字且数字前没有括号,将栈顶倍数后入栈
else if(Character.isDigit(chars[index])){
int num = 0; //括号后面的数字
while (index < chars.length && Character.isDigit(chars[index])){
num = num*10 + chars[index] - '0';
index++;
}
char top = stack.pop();
for (int j = 0; j < num; j++) {
stack.push(top);
}
}
}
//输出结果,从栈底开始输出
while (!stack.isEmpty()){
result.append(stack.pop());
}
String string = result.reverse().toString();
System.out.println(string);
}
}
}
}