首页 > 猿辅导20210731编程题第二道
头像
牛客_陈冠希
编辑于 2021-08-01 06:04
+ 关注

猿辅导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;
    }
}


全部评论

(1) 回帖
加载中...
话题 回帖

推荐话题

相关热帖

近期热帖

历年真题 真题热练榜 24小时
技术(软件)/信息技术类
查看全部

热门推荐