判断括号匹配

括号匹配(思路:遇到左括号时将右括号加入到栈中,遇到右括号则出栈同时与上一个入栈的括号比较,如果不是它的右括号,则不是对称的括号) 

package com.example.demo.utils;

import org.apache.commons.lang3.StringUtils;

import java.util.Arrays;
import java.util.List;
import java.util.Stack;

/**
 * 括号匹配
 */
public class BracketMatch {

    public static void main(String[] args) {
        String bracket = "({}[])";
        boolean ret = false;
        if (StringUtils.isEmpty(bracket)) {
            System.err.println("空串:" + ret);
        }
        if (bracket.length() % 2 != 0) {
            System.err.println("长度不是2的倍数:" + ret);
        }
        Stack<Character> stack = new Stack<>();

        char first = bracket.charAt(0);
        List<Character> leftBrackets = Arrays.asList('(', '[', '{');
        if (!leftBrackets.contains(first)) {
            System.err.println("不是以左括号开头的括号集合");
        }
        if (first == '(') {
            first = ')';
        }
        if (first == '[') {
            first = ']';
        }
        if (first == '{') {
            first = '}';
        }

        int length = bracket.length();
        char temp = 'c';
        for (int i = 0; i < length; i++) {
            char leftBracket = bracket.charAt(i);
            if (leftBracket == '{') {
                stack.push('}');
                temp = '}';
            }
            if (leftBracket == '(') {
                stack.push(')');
                temp = ')';
            }
            if (leftBracket == '[') {
                stack.push(']');
                temp = ']';
            }
            if (leftBracket == '}') {
                if (stack.size() == 1) {
                    if (first != stack.pop()) {
                        System.err.println("右}匹配1:" + ret);
                    }
                } else {
                    if (temp == 'c' || stack.pop() != temp)
                        System.err.println("右}匹配:" + ret);
                }
            }

            if (leftBracket == ']') {
                if (stack.size() == 1) {
                    if (first != stack.pop()) {
                        System.err.println("右]匹配1:" + ret);
                    }
                } else {
                    if (temp == 'c' || stack.pop() != temp)
                        System.err.println("右]匹配:" + ret);
                }
            }

            if (leftBracket == ')') {
                if (stack.size() == 1) {
                    if (first != stack.pop()) {
                        System.err.println("右)匹配1:" + ret);
                    }
                } else {
                    if (temp == 'c' || stack.pop() != temp)
                        System.err.println("右)匹配2:" + ret);
                }
            }
        }
        if (!stack.empty()) {
            System.err.println("栈非空:" + ret);
        }
    }

}

上一篇:ES6语法总结


下一篇:最权威的讲解Go 1.13中的错误处理