美文网首页
Valid Parentheses

Valid Parentheses

作者: Wenyue_offer | 来源:发表于2017-09-13 13:36 被阅读0次
class Solution {
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();
        
        for (char c : s.toCharArray()){
            if(c=='(' || c=='['|| c =='{'){
                stack.push(c);
            }
            if(c==')'){
                if(stack.isEmpty() || stack.pop() != '('){
                    return false;
                }
            }
            if(c=='}'){
                if(stack.isEmpty() || stack.pop() != '{'){
                    return false;
                }
            }
            if(c==']'){
                if(stack.isEmpty() || stack.pop() != '['){
                    return false;
                }
            }
        }
        return stack.isEmpty();
    }
}

相关文章

网友评论

      本文标题:Valid Parentheses

      本文链接:https://www.haomeiwen.com/subject/qmwksxtx.html