[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;
    }

    }

猜你喜欢

转载自www.cnblogs.com/ruoh3kou/p/9951405.html
今日推荐