Monday, November 25, 2013

LeetCode Problem : Longest Valid Parentheses

Problem


Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
For "(()", the longest valid parentheses substring is "()", which has length = 2.
Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4.

Code

int longestValidParentheses(string s) {
    // Note: The Solution object is instantiated only once and is reused by each test case.
    int n = s.size();
    int max_p = 0;
    int i = 0,base = 0;
    stack<int> st; 
    while(i < n){
        if(s[i] == '('){
            st.push(0);
        }
        else if(s[i] == ')'){
            if(st.empty()){
                base = 0;
            }
            else{
                int curr = st.top() + 1;
                st.pop();
                if(st.empty()){
                    base = base + curr;
                    if(max_p < base)
                    max_p = base;
                }
                else{
                int currbase = st.top() + curr;
                st.pop();
                st.push(currbase);
                if(max_p < currbase)
                    max_p = currbase;
                }
            }
        }
        ++i;
    }
    return 2*max_p;
}

No comments:

Post a Comment