LeetCode20-括号的匹配

Posted 不学无墅_NKer

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode20-括号的匹配相关的知识,希望对你有一定的参考价值。

 

 

 

class Solution {
    public boolean isValid(String s) {
        if (s == null || s.length() == 0) return true;
        /**
         * 解法1:
         */
        /*Stack<Character> stack = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == \'(\' || c == \'{\' || c == \'[\') {
                stack.push(c);
            }else {
                if (stack.isEmpty()) {
                    return false;
                }
                char temp = stack.pop();
                if (c == \')\' && temp != \'(\') return false;
                if (c == \'}\' && temp != \'{\') return false;
                if (c == \']\' && temp != \'[\') return false;
            }
        }
        return stack.isEmpty();*/
        /**
         * 解法2:
         */
        Stack<Character> stack = new Stack<>();
        for (char c : s.toCharArray()) {
            if (c == \'(\') {
                stack.push(\')\');
            }else if (c == \'[\') {
                stack.push(\']\');
            }else if (c == \'{\') {
                stack.push(\'}\');
            }else if (stack.isEmpty() || c != stack.pop()) {
                return false;
            }
        }
        return stack.isEmpty();
    }
}

 

以上是关于LeetCode20-括号的匹配的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 20. 有效的括号

LeetCode20-括号的匹配

leetcode 20 简单括号匹配

LeetCode 20. Valid Parentheses

python(LeetCode20-有效的括号)

20/32/22/856/301/921 Parentheses 括号匹配或者生成题