1 Star 0 Fork 0

luobg01/PFJ_coding

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
code041_longestValidParentheses.h 1.64 KB
一键复制 编辑 原始数据 按行查看 历史
luobg01 提交于 2024-01-03 16:42 . leetcode 32 最长括号
//
// Created by 罗炳国 on 2024/1/3.
//
#ifndef PFJ_CODE041_LONGESTVALIDPARENTHESES_H
#define PFJ_CODE041_LONGESTVALIDPARENTHESES_H
#include "commonHeader.h"
/**
* 给你一个只包含 '(' 和 ')' 的字符串,找出最长有效(格式正确且连续)括号子串的长度。
* 32 https://leetcode.cn/problems/longest-valid-parentheses/submissions/
* */
class code041_longestValidParentheses {
public:
int longestValidParentheses(string s) {
int N = s.size();
int ans = 0;
if (N == 0)
return ans;
vector<int> dp(N, 0);
for (int i = 1; i < N; i++) {
if (s[i] == ')') {
if (s[i - 1] == '(')
dp[i] = i > 2 ? 2 + dp[i - 2] : 2;
else { // ')'
if (i - dp[i - 1] - 1 >= 0 && s[i - dp[i - 1] - 1] == '(') {
dp[i] = dp[i - 1] + 2;
if (i - dp[i - 1] - 2 >= 0)
dp[i] += dp[i - dp[i - 1] - 2];
}
}
}
ans = max(ans, dp[i]);
}
return ans;
}
void test() {
string s("(()");
int ans = longestValidParentheses(s);
std::cout << s << ":" << ans << endl;
s = "(()(())())";
ans = longestValidParentheses(s);
std::cout << s << ":" << ans << endl;
s = ")()())";
ans = longestValidParentheses(s);
std::cout << s << ":" << ans << endl;
s = "()()))))()()(";
ans = longestValidParentheses(s);
std::cout << s << ":" << ans << endl;
}
};
#endif//PFJ_CODE041_LONGESTVALIDPARENTHESES_H
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C++
1
https://gitee.com/luobg01/pfj_coding.git
git@gitee.com:luobg01/pfj_coding.git
luobg01
pfj_coding
PFJ_coding
master

搜索帮助

23e8dbc6 1850385 7e0993f3 1850385