最长有效括号
Category Difficulty Likes Dislikes
algorithms Hard (28.90%) 451 -
Tags
Companies
给定一个只包含 ‘(’ 和 ‘)’ 的字符串,找出最长的包含有效括号的子串的长度。
示例 1:
输入: “(()”
输出: 2
解释: 最长有效括号子串为 “()”
示例 2:
输入: “)()())”
输出: 4
解释: 最长有效括号子串为 “()()”
分析
- 利用动态规划,构建dp[],dp[i]表示str[0…i]强制以i结尾时的最长有效子串长度。
- 如果遍历到左括号,直接为0
- 如果遍历到右括号,需考虑两个值:i-dp[i-1]-1和i-dp[i-1]-2
- i-dp[i-1]-1是该右括号要匹配的值,该值必须为左括号,否则有效子串长度为0
- i-dp[i-1]-2是该右括号要匹配的值的前一个,有效子串需要加上该位置对应值。
/*
* @lc app=leetcode.cn id=32 lang=java
*
* [32] 最长有效括号
*/
// @lc code=start
class Solution {
public int longestValidParentheses(String s) {
char[] chars = s.toCharArray();
int[] dp = new int[chars.length];
int res = 0;
for(int i = 1; i < chars.length; i++){
if(chars[i] == ')'){
// i-dp[i-1]-1是dp[i-1]有效子串的前一个。如"(())"
if(i-dp[i-1]-1 >= 0 && chars[i-dp[i-1]-1] == '(' ){
//需判断dp[i-dp[i-1]-2]
dp[i] = dp[i-1]+ 2 + (i-dp[i-1]-2 >= 0?dp[i-dp[i-1]-2]:0);
}
}
res = Math.max(res, dp[i]);
}
return res;
}
}
// @lc code=end
来源:CSDN
作者:只臭脚
链接:https://blog.csdn.net/weixin_44851932/article/details/103835568