天天看点

栈应用—字符串括号匹配问题

利用栈,可以解决一些算法问题,比如括号匹配、逆波兰表达式...

以下demo,解决括号匹配问题:

BracketStr.java

/**
 * @Author: ltx
 * @Description: 栈应用-字符串括号匹配问题
 */
public class BracketStr {
    private static Boolean isValid(String str) {
        //拆成char[]
        char[] chars = str.toCharArray();
        Stack<Character> left = new Stack<>();
        for (Character ch : chars) {
            //遇左括号,放入栈中
            if (ch.equals('{') || ch.equals('(') || ch.equals('[')) {
                left.push(ch);
            }
            //遇右括号,先判空,然后判断成对,不成对的则为不匹配
            if (ch.equals('}') || ch.equals(')') || ch.equals(']')) {
                //判断栈空
                if (left.isEmpty()) {
                    return false;
                }
            }
            //判断成对
            if (ch.equals('}')) {
                if (!left.pop().equals('{')) {
                    return false;
                }
            }
            if (ch.equals(')')) {
                if (!left.pop().equals('(')) {
                    return false;
                }
            }
            if (ch.equals(']')) {
                if (!left.pop().equals('[')) {
                    return false;
                }
            }
        }
        //判断栈空
        if (left.isEmpty()) {
            return true;
        }
        return false;
    }

    public static void main(String[] args) {
//        String str = "kh(((we)w(fwe)(456)[34][{{66555}}]56))6655";
//        String str = "sagjhsjakldgh2357465768";
//        String str = "[][]()(){}";
        String str = "we[]sd12[]23()]we(546456)dd{r6789679}";
        System.out.println(isValid(str));
    }
}
           

继续阅读