[LeetCode] 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.

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<1)   return 0;
        vector<int > table(len+1,0);
        int cnt = 0;
        if(s[0]=='(')   cnt++;
        else    cnt --;
        int retMax = 0;
        for(int i=1;i<len;i++){
            if(s[i]=='('){
                if(cnt<0)   cnt=1;
                else    cnt++;
                continue;
            }
            cnt--;
            if(cnt>=0){
                if(s[i-1]=='(') table[i+1] = table[i-1]+2;
                else{
                    if(s[i-1-table[i]]=='(')
                        table[i+1] = table[i-1-table[i]]+2+table[i];
                }
                if(retMax<table[i+1])   retMax = table[i+1];
            }
        }
        return retMax;
    }
};

int main()
{
    Solution sol;
    cout<<sol.longestValidParentheses("()(())")<<endl;
    return 0;
}
原文地址:https://www.cnblogs.com/Azhu/p/4416027.html