/*
* @lc app=leetcode.cn id=32 lang=cpp
*
* [32] 最长有效括号
*
* https://leetcode-cn.com/problems/longest-valid-parentheses/description/
*
* algorithms
* Hard (35.41%)
* Likes: 1396
* Dislikes: 0
* Total Accepted: 173.1K
* Total Submissions: 488.8K
* Testcase Example: '"(()"'
*
* 给你一个只包含 '(' 和 ')' 的字符串,找出最长有效(格式正确且连续)括号子串的长度。
*
*
*
*
*
* 示例 1:
*
*
* 输入:s = "(()"
* 输出:2
* 解释:最长有效括号子串是 "()"
*
*
* 示例 2:
*
*
* 输入:s = ")()())"
* 输出:4
* 解释:最长有效括号子串是 "()()"
*
*
* 示例 3:
*
*
* 输入:s = ""
* 输出:0
*
*
*
*
* 提示:
*
*
* 0
* s[i] 为 '(' 或 ')'
*
*
*
*
*/
// @lc code=start
class Solution {
public:
int longestValidParentheses(string s) {
// 方法一: 通过动态规划
// dp[i]表示以i结尾的最长有效括号长度;
int n = s.size();
if(n < 2)
return 0;
vector<int> dp(n,0);
int res = 0;
for(int i = 1;i<n;i++)
{
if(s[i] == ')')
{
int pre = i - dp[i-1] -1;
if (pre >= 0 and s[pre] == '(')
{
dp[i] = dp[i-1]+2;
// 处理独立的括号对的情形 类似()()、()(())
if (pre > 0)
{
dp[i] += dp[pre-1];
}
res = max(res,dp[i]);
}
}
}
return res;
// 方法二:通过栈的思路
// stack<int> st;
// int res = 0;
// int tmp = 0;
// bool is_continue = false;
// for(int i = 0;i<s.size();i++)
// {
// if(!st.empty())
// {
// if(s[st.top()] == '(' and s[i] == ')')
// {
// st.pop();
// }
// else
// {
// st.push(i);
// }
// }
// else
// {
// st.push(i);
// }
// }
// int end = s.size();
// while(!st.empty())
// {
// res = max(end - st.top()-1,res);
// end = st.top();
// st.pop();
// }
// res = max(end ,res);
// return res;
}
};
// @lc code=end
11-22
478
07-04
842
08-05
1442
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交