leetcode-----20. 有效的括号

代码

class Solution {
    public boolean isValid(String str) {
        Stack<Character> stk = new Stack<>();
        char s[] = str.toCharArray();

        for (int i = 0; i < str.length(); ++i) {
            if (s[i] == '(' || s[i] == '[' || s[i] == '{') {
                stk.push(s[i]);
            } else if (s[i] == ')') {
                if (stk.empty() || stk.peek() != '(') return false;
                stk.pop();
            } else if (s[i] == ']') {
                if (stk.empty() || stk.peek() != '[') return false;
                stk.pop();
            } else if (s[i] == '}') {
                if (stk.empty() || stk.peek() != '{') return false;
                stk.pop();
            } 
        }
        return stk.empty();
    }
}
原文地址:https://www.cnblogs.com/clown9804/p/13121692.html