Title address: Longest Valid Parentheses
Introduction:
Given a string containing only '(' and ')', find the length of the longest substring containing valid parentheses.
Example 1: Input: "(()" Output: 2 Explanation: The longest valid parentheses substring is "()" Example 2: Input: ")()())" Output: 4 Explanation: The longest valid parentheses substring is "()()"
Topic analysis:
1. Use of stack
The first thing we think about is the stack solution. There is only one kind of bracket here, so the right bracket is a special case to consider. When a closing bracket appears, if there is no corresponding opening bracket corresponding to it, the closing bracket will not be included in the longest field and the string will be split. In conclusion, the following points need to be noted:
- When the current character is left bracket, it will not be processed, and the current position will be recorded for the convenience of length;
- When the current character is a closing bracket, if there is no corresponding most bracket, the next consecutive valid bracket must be after this character. When there are corresponding brackets, there are two situations. One is that the right bracket just matches the left bracket, so this string is a valid bracket; the other is that there are multiple left brackets, so you can find the position of the left bracket closest to the right bracket, and then you can get the longest bracket under the current position.
C++ version:
class Solution { public: int longestValidParentheses(string s) { int res = 0, start = 0; stack<int> stc; for (int i = 0; i < s.size(); ++i) { if (s[i] == '(') stc.push(i); else if (s[i] == ')') { if (stc.empty()) start = i + 1; else { res = max(res, i - start + 1); stc.pop(); res = stc.empty() ? max(res, i - start + 1) : max(res, i - stc.top()); } } } return res; } };
2. Dynamic planning
C++ version
class Solution { public: int longestValidParentheses(string s) { if (s.length() <= 1) return 0; int ans = 0; int dp[s.size()]; memset(dp,0,sizeof(dp)); for (int i = 1; i < s.size(); i++) { if (s[i] == ')') { if (s[i - 1] == '(') dp[i] = (i >= 2 ? dp[i - 2] : 0) + 2; else if (i - dp[i - 1] > 0 && s[i - dp[i - 1] - 1] == '(') { dp[i] = dp[i - 1] + ((i - dp[i - 1]) >= 2 ? dp[i - dp[i - 1] - 2] : 0) + 2; } ans = max(ans, dp[i]); } } return ans; } };