华为OD机试真题 - 最大括号深度

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String word = in.nextLine();
        System.out.println(getResult(word));
    }

    public static int getResult(String word) {
        Stack<Character> stacks = new Stack<>();

        int max = 0;
        boolean isInvalid = false;
        for (int i = 0; i < word.length(); i++) {
            switch (word.charAt(i)) {
                case '(' : {
                    stacks.add('(');
                    max = Math.max(max, stacks.size());
                } break;
                case '[' : {
                    stacks.add('[');
                    max = Math.max(max, stacks.size());
                } break;
                case '{' : {
                    stacks.add('{');
                    max = Math.max(max, stacks.size());
                } break;
                case ')' : {
                    if (stacks.pop() != '(')
                        isInvalid = true;
                    break;

                }
                case ']' : {
                    if (stacks.pop() != '[')
                        isInvalid = true;
                    break;
                }
                case '}' : {
                    if (stacks.pop() != '{')
                        isInvalid = true;
                    break;
                }
                default:break;
            }
        }
        if (isInvalid) return 0;
        return max;
    }
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务