1. 程式人生 > >[leetcode] 20. Valid Parentheses (easy)

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

    }