Parenthesis/Brackets Matching using Stack algorithm

前端 未结 30 2704
你的背包
你的背包 2020-11-27 11:39

For example if the parenthesis/brackets is matching in the following:

({})
(()){}()
()

and so on but if the parenthesis/brackets is not mat

30条回答
  •  情深已故
    2020-11-27 12:08

    public String checkString(String value) {
        Stack stack = new Stack<>();
        char topStackChar = 0;
        for (int i = 0; i < value.length(); i++) {
            if (!stack.isEmpty()) {
                topStackChar = stack.peek();
            }
            stack.push(value.charAt(i));
            if (!stack.isEmpty() && stack.size() > 1) {
                if ((topStackChar == '[' && stack.peek() == ']') ||
                        (topStackChar == '{' && stack.peek() == '}') ||
                        (topStackChar == '(' && stack.peek() == ')')) {
                    stack.pop();
                    stack.pop();
                }
            }
        }
        return stack.isEmpty() ? "YES" : "NO";
    }
    

提交回复
热议问题