用栈检查括号合法性 20. Valid Parentheses

简单题,吃饭前写着玩玩

import java.util.*;
class Solution {
    public boolean isValid(String s) {
        if(s.length() == 0)
            return true;
        boolean ret = true;
        int length = s.length();
        Stack stack = new Stack();
        for(int i=0; i < length; i++) {
            char parenth = s.charAt(i);
            if(parenth == '[' || parenth == '{' || parenth == '(') {
                stack.push(parenth);
            }
            else if(parenth == ']' || parenth == '}' || parenth == ')') {
                if(stack.empty())
                    return false;
                char opposite = stack.pop();
                if(parenth == ']' && opposite != '[')
                    ret = false;
                else if(parenth == '}' && opposite != '{')
                    ret = false;
                else if(parenth == ')' && opposite != '(')
                    ret = false;
            }
        }
        if(!stack.empty())
            return false;
        return ret;
    }
}

你可能感兴趣的:(算法)