Wednesday, January 7, 2015

LeetCode 20: 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.
public class Solution {
    public boolean isValid(String s) {
        // If encounter left bracket, push it to the stack;
        // If encounter right bracket, pop the stack to verify if they are pair.
        int n = s.length();
        
        if (n==0 || n%2==1)
            return false;
            
        Map<String, String> map = new HashMap<>();
        Stack<String> stack = new Stack<>();
        
        map.put(")", "(");
        map.put("}", "{");
        map.put("]", "[");
        
        String s1;
        String s2;
        
        for (int i = 0; i < n; i++)
        {
            s1 = String.valueOf(s.charAt(i));
            
            // If s1 is left bracket or not
            if (map.containsValue(s1))
                // Push left bracket s1
                stack.push(s1);
            else
            {
                // s1 is right bracket
                // If stack is empty, it represents that the number of right brackets is more than that of left brackets.
                if (stack.isEmpty())
                    return false;
                else
                {
                    // Pop left bracket s2 related to right bracket s1
                    s2 = stack.pop();
                    
                    // If s2 and s1 is not a pair
                    if (!map.get(s1).equals(s2))
                        return false;
                }
            }
        }
        
        // If stack is not empty, it represents that the number of left brackets is more than that of right brackets.
        if (!stack.isEmpty())
            return false;
        
        return true;
    }
}

No comments:

Post a Comment