Longest Valid Parentheses

来源:互联网 发布:sql developer下载 编辑:程序博客网 时间:2024/06/07 04:51

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.


Solution:

class Solution {public:    int longestValidParentheses(string s) {        stack<int> sc;        int i = 0, index = 0, maxlen = 0;        while(i < s.length())        {            if(s[i] == '(') sc.push(i);            else            {                if(sc.empty()) index = i + 1;                else                {                    sc.pop();                    if(sc.empty()) maxlen= max(maxlen, i - index + 1);                    else maxlen = max(maxlen, i - sc.top());                }            }            i++;        }        return maxlen;    }};


0 0
原创粉丝点击