Monday, February 25, 2013

[LeetCode] Valid Parentheses

Thought:
Trivial using stack.

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

No comments:

Post a Comment