Friday, April 11, 2014

LeetCode: 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.


Use a stack to help matching

C++ Code:

/*
 * func: valid_parentheses
 * goal: to check if parentheses in current string match
 * @param s: input string
 * return: true or false
 */
/*
 * Use stack
 * complexity: time O(n), space O(n)
 */
bool valid_parentheses(const string &s){
    stack<char> stk;
    for(auto it = s.cbegin(); it != s.cend(); ++it){
        if(*it == '(' || *it == '[' || *it == '{'){
            stk.emplace(*it);
        }else if(!stk.empty()){
            if(*it == ')' && stk.top() == '('){
                stk.pop();
            }else if(*it == ']' && stk.top() == '['){
                stk.pop();
            }else if(*it == '}' && stk.top() == '{'){
                stk.pop();
            }else{
                return false;
            }
        }else{
            return false;
        }
    }
    if(stk.empty()){
        return true;
    }else{
        return false;
    }
}

Python Code:

# func: to check if parentheses in the string match
# @param s: input string
# @return: True or False
# complexity: time O(n), space O(n)
def valid_parentheses(s):
    if not s:
        return False
    else:
        stack = []
        for parenthesis in s:
            if parenthesis in '([{':
                stack.append(parenthesis)
            elif stack and (parenthesis == ']' and stack[-1] == '[' 
or parenthesis == ')' and stack[-1] == '(' or
            parenthesis == '}' and stack[-1] == '{'):
                stack = stack[:-1]
            else:
                return False

        if not stack:
            return True
        else:
            return False

No comments:

Post a Comment