20. Valid Parentheses

原创
2016/10/10 19:49
阅读数 12

20. Valid Parentheses

  • Difficulty: Easy

 

Given a string containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

public class Solution {
    public boolean isValid(String s) {
        if(s==null||s.length()<=0)
            return true;
        Stack<Integer> stack=new Stack<>();
        char[] chars=s.toCharArray();
        boolean flag=true;
        for(int i=0;i<s.length();i++){
            switch (chars[i]){
                case '(':
                    stack.push(-1);
                    break;
                case'[':
                    stack.push(-2);
                    break;
                case'{':
                    stack.push(-3);
                    break;
                case ')':
                    if(stack.isEmpty()||1+stack.pop()!=0)
                        flag&=false;
                        break;
                case']':
                    if(stack.isEmpty()||2+stack.pop()!=0)
                        flag&=false;
                        break;
                case'}':
                    if(stack.isEmpty()||3+stack.pop()!=0)
                        flag&=false;
                        break;
                default:
                    break;
            }
            if(!flag)
                break;
        }
        return flag&stack.isEmpty();
    }
}

 

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部