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.

Stack

Time Complexity
O(n)
Space Complexity
O(n)

思路

Traverse the string, if it is "([{" , push into stack, if it is ")}]", check if the stack is empty first, if it is empty, return invalid. If it is not empty, check if the stack.pop() match ")}]".

代码

public boolean isValid(String s) {
    //corner case
    if(s == null || s.length() < 2) return false;
    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;
            if(c == ')'){
                if(!stack.isEmpty() && stack.pop() != '(') return false; 
            }else if(c == '}'){
                if(!stack.isEmpty() && stack.pop() != '{') return false;
            }else if(c == ']'){
                if(!stack.isEmpty() && stack.pop() != '[') return false;
            }
        }
    }
    return stack.isEmpty();
}

Test Cases

[])
){
()[]{}
(]
([)]


annielulu
5 声望5 粉丝