32. Longest Valid Parentheses
https://leetcode.com/problems/longest-valid-parentheses/description/
Thoughts
/*
* @lc app=leetcode id=32 lang=cpp
*
* [32] Longest Valid Parentheses
*
* https://leetcode.com/problems/longest-valid-parentheses/description/
*
* algorithms
* Hard (26.15%)
* Likes: 2213
* Dislikes: 100
* Total Accepted: 212.3K
* Total Submissions: 809.8K
* Testcase Example: '"(()"'
*
* Given a string containing just the characters '(' and ')', find the length
* of the longest valid (well-formed) parentheses substring.
*
* Example 1:
*
*
* Input: "(()"
* Output: 2
* Explanation: The longest valid parentheses substring is "()"
*
*
* Example 2:
*
*
* Input: ")()())"
* Output: 4
* Explanation: The longest valid parentheses substring is "()()"
*
*
*/
class Solution {
public:
int longestValidParentheses(string s) {
const int N = s.size();
vector<int> dp(N);
int res = 0;
for (int i = 1; i < N; ++i) {
if (s[i] != ')') continue;
const int lp = i - 1 - dp[i - 1];
if (lp >= 0 && s[lp] == '(') dp[i] = i - lp + 1 + (lp == 0 ? 0 : dp[lp - 1]);
res = max(res, dp[i]);
}
return res;
}
};
Last updated