问题描述:
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"()()"
源码:
栈方法:
用一个栈,栈顶存索引,很好解决,效率也很可以,时间上95%,空间还是100%(最近leetcode咋弄都是100%,java随便一弄就是10%以下,难道虚拟机那么占内存)
class Solution {
public:
int longestValidParentheses(string s) {
int n = s.size();
if(n==0) return 0;
stack<int> help;
int result = 0;
for(int i=0; i<n; i++){
if(s[i]==')' && !help.empty() && s[help.top()]=='('){
help.pop();
if(help.empty()) result = max(result, i+1);
else result = max(result, i-help.top());
}
else help.push(i);
}
return result;
}
};
动态规划法:
注意从1开始遍历。时间和空间都是100%,Perfect!!!
class Solution {
public:
int longestValidParentheses(string s) {
int n = s.size();
if(n==0) return 0;
vector<int> dp(n, 0);
int result = 0;
for(int i=1; i<n; i++){
if(s[i]=='(') dp[i] = 0;
else{
int index = i-dp[i-1]-1;
if(index>=0 && s[index]=='('){
dp[i] = dp[i-1]+2;
if(index-1>=0) dp[i]+=dp[index-1];
}
}
// cout<<result<<endl;
result = max(result, dp[i]);
}
return result;
}
};
双向扫描法:
非常规做法,不做详解,效率和第一种差不多。
class Solution {
public:
int longestValidParentheses(string s) {
int n = s.size();
if (n == 0) return 0;
int ret = 0;
// 前向扫描
int l_cnt = 0, r_cnt = 0;
for (int i = 0; i < n; ++i) {
if (s[i] == '(')
l_cnt++;
else
r_cnt++;
if (l_cnt < r_cnt)
l_cnt = r_cnt = 0; // 而今迈步从头越
else if (l_cnt == r_cnt)
ret = max(ret, l_cnt * 2);
}
// 反向扫描
l_cnt = r_cnt = 0;
for (int i = n - 1; i >= 0; --i) {
if (s[i] == '(')
l_cnt++;
else
r_cnt++;
if (l_cnt > r_cnt)
l_cnt = r_cnt = 0;
else if (l_cnt == r_cnt)
ret = max(ret, r_cnt * 2);
}
return ret;
}
};