Tuesday, September 15, 2015

Valid Parentheses | Leetcode

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.

---

Solution: Maintain a stack of brackets. When we see an opening bracket, push it to the stack. When we see a closing bracket, make sure the top of the stack has an opening bracket that matches that closing bracket.
public class Solution {
    public boolean isValid(String s) {
        LinkedList<Character> stack = new LinkedList<>();
        
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            
            if (c == '(' || c == '{' || c == '[') {
                stack.push(c);
                continue;
            }
            
            char match;
            
            if (c == ')') {
                match = '(';
            } else if (c == '}') {
                match = '{';
            } else if (c == ']') {
                match = '[';
            } else {
                continue;
            }
            
            if (stack.isEmpty() || stack.pop() != match) {
                return false;
            }
        }
        
        return stack.isEmpty();
    }
}

No comments: