Longest Valid Parentheses

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Longest Valid Parentheses相关的知识,希望对你有一定的参考价值。

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.

 

Subscribe to see which companies asked this question

Show Tags
Show Similar Problems
 
class Solution {
public:
    int longestValidParentheses(string s) {
        int length = s.length();
        if (0 == length) {
            return 0;
        }
        int max_len = 0;
        int i = 0;
        int start = 0;
        stack<int> s_i;
        for (i=0; i<length; i++) {
            if (s[i] == () {
                s_i.push(i);
            } else if (s[i] == ) && !s_i.empty()) {
                //int left = s_i.top();
                s_i.pop();
                if (s_i.empty()) {
                    max_len = max(max_len, i - start + 1);
                } else {

                    max_len = max(max_len, i - s_i.top());
                    cout << "max len when not empty is " << max_len << endl;
                }
            } else {
                start = i + 1;
            }
        }
        return max_len;
    }
};

 

以上是关于Longest Valid Parentheses的主要内容,如果未能解决你的问题,请参考以下文章

Longest Valid Parentheses

Longest Valid Parentheses

Longest Valid Parentheses

32. Longest Valid Parentheses

32. Longest Valid Parentheses

32. Longest Valid Parentheses