32. 最长有效括号 Longest Valid Parentheses
Given a string containing just the characters '('
and ')'
, find the length of the longest valid (well-formed) parentheses substring.
Input: s = "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()".
方法一:
动态规划
如果最右为‘(’,放弃
如果最右为‘)’,
如果i-1为‘(’, dp[i] = dp[i-2] +2
如果i-1为‘)’,且i - dp[i - 1] -1 为'(',dp[i]=dp[i - 1]+dp[i - dp[i - 1] -2] +2
public int longestValidParentheses(String s) { int maxans = 0; int [] dp = new int[s.length()]; for(int i = 1; i < s.length(); i++){ if(s.charAt(i) == ')'){ if(s.charAt(i - 1) == '('){ dp[i] = i >= 2 ? (dp[i - 2] + 2) : 2; }else if(i - dp[i -1] > 0 && s.charAt(i - dp[i - 1] -1) == '('){ dp[i] = dp[i - 1] + ((i - dp[i - 1]) >= 2 ? dp[i - dp[i - 1] -2] : 0) + 2; } maxans = Math.max(maxans, dp[i]); } } return maxans; }
参考链接:
https://leetcode.com/problems/longest-valid-parentheses/
https://leetcode-cn.com/problems/longest-valid-parentheses