2014年2月25日星期二

LeetCode - Valid Parentheses

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.


Have you been asked this question in an interview?

public class Solution {
    public boolean isValid(String s) {
        if(s==null) {
            return true;
        }
        Stack<Character> stk = new Stack<Character>();
        for(int i=0;i<s.length();i++) {
            char c= s.charAt(i);
            if(c=='('||c=='{'||c=='[') {
                stk.push(c);
            } else if(stk.isEmpty()) {
                return false;
            } else {
                char c2 = stk.pop();
                if(!((c==')'&&c2=='(') || (c=='}'&&c2=='{') || (c==']'&&c2=='['))) {
                    return false;
                }
            }
        }
        if(stk.isEmpty()) {
            return true;
        } else {
            return false;
        }
    }
}

没有评论:

发表评论