【LeetCode】32. Longest Valid Parentheses(C++)
阿新 • • 發佈:2018-12-26
地址:https://leetcode.com/problems/longest-valid-parentheses/
題目:
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 “()()”
理解:
尋找一個字串中有效的括號
實現1:
基於動態規劃的實現。
如果是一個有效的子串,一定以')'
結束。因此,對於‘(’
,保持0就可以了。
- 若
s[i]==')'
且s[i-1]==‘(’
,則dp[i]=dp[i-2]+2
; - 若前面為
')'
,則需要通過dp[i-1]
找到前面有效子串的起始,並判斷更靠前一位是否是'('
。並且,還要加上更靠前一位的已經有效子串的長度。
class Solution {
public:
int longestValidParentheses(string s) {
vector<int> dp(s.length(), 0);
int maxCnt = 0;
for (int i = 1; i < s.length(); ++i) {
if (s[i] == ')') {
if (s[i - 1] == '(')
dp[i] = i -2 >= 0 ? dp[i - 2] + 2 : 2;
else if (i - dp[i - 1] - 1 >= 0 && s[i - dp[i - 1] - 1] == '(') {
dp[i] = dp[i - 1] + 2 + ((i - dp[i - 1] - 2 >= 0) ? dp[i - dp[i - 1] - 2] : 0);
}
maxCnt = max(maxCnt, dp[i]);
}
}
return maxCnt;
}
};
實現2:
從左到右和從右到左,將字串遍歷兩次
class Solution {
public:
int longestValidParentheses(string s) {
int maxCnt = 0;
int left = 0, right = 0;
for (int i = 0; i < s.length(); ++i) {
if (s[i] == '(')
++left;
else
++right;
if (left == right)
maxCnt = max(maxCnt, 2 * right);
else if (right >= left)
left = right = 0;
}
left = right = 0;
for (int i = s.length()-1; i >=0; --i) {
if (s[i] == '(')
++left;
else
++right;
if (left == right)
maxCnt = max(maxCnt, 2 * left);
else if (left >= right)
left = right = 0;
}
return maxCnt;
}
};
實現3:
使用一個棧保留位置。
class Solution {
public:
int longestValidParentheses(string s) {
stack<int> stk;
stk.push(-1);
int maxL=0;
for(int i=0;i<s.size();i++)
{
int t=stk.top();
if(t!=-1&&s[i]==')'&&s[t]=='(')
{
stk.pop();
maxL=max(maxL,i-stk.top());
}
else
stk.push(i);
}
return maxL;
}
};