Monday, November 25, 2013

LeetCode Problem : Valid Parentheses

Problem

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.

Code

bool isValid(string s) {
    // Note: The Solution object is instantiated only once and is reused by each test case.
    int n = s.size();
    if(n == 0)
        return true;
    map<char,char> paren;
    paren.insert(make_pair(')','('));
    paren.insert(make_pair('}','{'));
    paren.insert(make_pair(']','['));
    stack<char> st;
    for(int i = 0; i < n; ++i){
        char c = s[i];
        if(c == '(' || c == '{' || c == '[')
        st.push(c);
        else if(c == ')' || c == '}' || c == ']'){
            if(st.empty())
                return false;
            char tp = st.top();
            if(tp != paren[c])
                return false;
            st.pop();
        }
    }
    return st.empty();
}

No comments:

Post a Comment