[Leetcode] Longest Valid Parentheses

来源:互联网 发布:免备案空间和域名购买 编辑:程序博客网 时间:2024/05/01 23:50

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.

#include <stack>using namespace std;class Solution {public:    int longestValidParentheses(string s) {        // Start typing your C/C++ solution below        // DO NOT write int main() function              int maxLength = 0;       int size = s.size();       stack<int> left;        if(size<=0) return 0;       int top = size;              for(int i = 0; i<size; i++)       {           if(s[i]=='(')           {               left.push(i);           }           else           {               if(left.empty())               {                   top = i + 1;//指向下一个为")"的index               }               else               {                   int tmp = left.top();                   top = min(top,tmp);                   left.pop();                   if(left.empty()) maxLength = max(i-top+1,maxLength);                   else maxLength = max(i-left.top(),maxLength); //注意:为什么是left.top()而不是tmp-1呢?考虑"(()()"的情况。               }           }       }              return maxLength;    }};