Saturday, June 27, 2015

Valid Parentheses

Given a string containing just the characters '(', ')''{''}''[' and']', determine if the input string is valid.
Have you met this question in a real interview?
Yes

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

public class Solution {
    /**
     * @param s A string
     * @return whether the string is a valid parentheses
     */
    public boolean isValidParentheses(String s) {
        // Write your code here
        Stack<Character> stack = new Stack<Character>();
        for(int i = 0; i < s.length(); i++){
            char c = s.charAt(i);
            if(c == '(' || c == '{' || c == '['){
                stack.push(c);
            } else if(stack.isEmpty()) return false;
            else if(c == ')' && stack.peek() != '(') return false;
            else if(c == '}' && stack.peek() != '{') return false;
            else if(c == ']' && stack.peek() != '[') return false;
            else {
                stack.pop();
            }    
        }
        return stack.isEmpty();
    }
}

No comments:

Post a Comment