leetcode 032 —— Longest Valid Parentheses

来源:互联网 发布:中国历年实际gdp数据 编辑:程序博客网 时间:2024/05/22 03:53

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.


思路:普通求解会超时,采用动态规划,动态数组d[i] 表示从i开始的最长有效字符串

class Solution {public:int longestValidParentheses(string s) {int n = s.size();int *d = new int[n];int max=0;for (int i = 0; i < n; i++)d[i] = 0;for (int i = n - 2; i >= 0; i--){if (s[i] == '('){int j = i + 1 + d[i + 1];if (j<n&&s[j] == ')'){d[i] = d[i + 1] + 2;if (j + 1 < n){d[i] += d[j + 1];}}max = max > d[i] ? max : d[i];}}return max;}}a;



0 0