[leetcode] 20. Valid Parentheses (easy)

Posted Ruoh3kou

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[leetcode] 20. Valid Parentheses (easy)相关的知识,希望对你有一定的参考价值。

原题链接

匹配括号
思路:
用栈,遍历过程中,匹配的成对出栈;结束后,栈空则对,栈非空则错。
Runtime: 4 ms, faster than 99.94% of Java

class Solution {
    public boolean isValid(String s) {
        Stack<Character> sta = new Stack<Character>();

        for (int i = 0; i < s.length(); i++) {
            char temp = s.charAt(i);
            if (temp == ‘[‘ || temp == ‘(‘ || temp == ‘{‘) {
            sta.push(temp);
            } else {
            if (sta.isEmpty())
                return false;
            char top = ‘ ‘;
            if (temp == ‘]‘)
                top = ‘[‘;
            if (temp == ‘)‘)
                top = ‘(‘;
            if (temp == ‘}‘)
                top = ‘{‘;
            if (top == sta.peek())
                sta.pop();
            else
                return false;
            }
        }
        return sta.isEmpty() ? true : false;
    }

    }



以上是关于[leetcode] 20. Valid Parentheses (easy)的主要内容,如果未能解决你的问题,请参考以下文章

leetcode20. Valid Parentheses

[LeetCode]20. Valid Parentheses

[LeetCode]20 Valid Parentheses 有效的括号

LeetCode OJ 20Valid Parentheses

Leetcode 20. Valid Parentheses

LeetCode 20. Valid Parentheses