[LeetCode] Longest Valid Parentheses 动态规划

时间:2023-12-18 23:34:20

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.

Hide Tags

Dynamic Programming String

 

  其实就是判断最常合法长度
如果当前字符为'(' 忽略。
如果为 ')':
1. 前一字符为 '(',那么长度是前二字符的最长合法长度+2.
2. 前一字符为')',那么获得前一字符的最长合法长度tmpLen
  a. 如果 前tmpLen+1  项是'(',那么便是合法的,取值为前tmpLen+1+1 项的长度  + tmpLen+2.
  b. 为')',配对失败,忽略。
最后返回最长的。
#include <string>
#include <iostream>
#include <vector>
using namespace std; class Solution {
public:
int longestValidParentheses(string s) {
int len = s.length();
if(len<) return ;
vector<int > table(len+,);
int cnt = ;
if(s[]=='(') cnt++;
else cnt --;
int retMax = ;
for(int i=;i<len;i++){
if(s[i]=='('){
if(cnt<) cnt=;
else cnt++;
continue;
}
cnt--;
if(cnt>=){
if(s[i-]=='(') table[i+] = table[i-]+;
else{
if(s[i--table[i]]=='(')
table[i+] = table[i--table[i]]++table[i];
}
if(retMax<table[i+]) retMax = table[i+];
}
}
return retMax;
}
}; int main()
{
Solution sol;
cout<<sol.longestValidParentheses("()(())")<<endl;
return ;
}