猿辅导20210731编程题第二道
给定字符串让你求一共有多少个括号,[]代表一个括号,[]2代表两个括号,[][]2代表3个括号,[[]2]3代表9个括号(有三个括号,每个括号内有两个小括号),[[][]2]3代表12个括号。以此类推。
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String s = in.nextLine();
System.out.println(getRes(s));
//[][[][][]2]3 16
//[][][[[]3[]2]2]2 28
}
public static int getRes(String s) {
Stack<Integer> stack = new Stack<>();
char[] arr = s.toCharArray();
for (int i = 0; i < arr.length; i++) {
if (arr[i] == '[') {
stack.push(0);
} else {
if (stack.peek() == 0) {
int t = 0;
while (i + 1 < arr.length && arr[i + 1] != '[' && arr[i + 1] != ']') {
i++;
t = t * 10 + Integer.parseInt(String.valueOf(arr[i]));
}
if (t == 0) t = 1;
stack.pop();
stack.add(t);
} else {
int inScore = 0;
while (stack.peek() != 0) {
inScore += stack.peek();
stack.pop();
}
stack.pop();
int t = 0;
while (i + 1 < arr.length && arr[i + 1] != '[' && arr[i + 1] != ']') {
i++;
t = t * 10 + Integer.parseInt(String.valueOf(arr[i]));
}
stack.add((inScore + 1) * t);
}
}
}
int res = 0;
while (!stack.empty()) {
res += stack.pop();
}
return res;
}
}
查看14道真题和解析
汤臣倍健公司氛围 373人发布