LeetCode: Longest Valid Parentheses

来源:互联网 发布:数控g72编程视频 编辑:程序博客网 时间:2024/05/02 01:08

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.

昨晚开始做的,刚开始以为只要数就行了,但是总有几个case过不了。看了tingmei大神的博客后,认识到了自己的错误。今天中午起来重新编过。


class Solution {public:    int longestValidParentheses(string s) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        int nSize = s.size();        int max = 0;        int begin = nSize;// where a part of legal parentheses begin        stack<int> stk;        for(int i = 0; i< nSize; ++i){            if(s[i] == '('){                stk.push(i);            }            else if(!stk.empty()){                int tmp = stk.top();                stk.pop();                begin = begin < tmp ? begin : tmp;                if(stk.empty())                    max = max > i - begin + 1 ? max : i - begin +1;                else                    max = max > i - stk.top()? max : i - stk.top();            }            else{                begin = i + 1;            }        }        return max;    }};


原创粉丝点击