Thursday, February 5, 2015

Longest Valid Parentheses -- LeetCode

[Question]
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.

[Analysis]
The length of the valid parentheses substring is: the index of "the next invalid character" - the index of "the last known invalid character" - 1. For example, in the sequence "(()(", the length is 3-0-1 = 2.

Use a stack to trace and remove the valid parentheses from the string. Trace means the stack needs to store the index of each character in the string. "The next invalid character" is the character to push into stack; "the last known invalid character" is the character in the top of stack.

[Solution]
class Solution {
public:
    int longestValidParentheses(string s) {
        stack<int> st;
       
        int len=0;
        for (int i=0; i<s.size(); i++) {
            if (!st.empty() && s[st.top()]=='(' && s[i]==')' ) {
                st.pop();
                len = max(len, st.empty()?i+1:i-st.top() );
            }
            else
                st.push(i);
        }
        return len;
    }
};

No comments:

Post a Comment