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 “()()”
三种方法,一种是用栈的方法,一种是两遍扫描,还有一种是DP
栈:
class Solution {
public:
int longestValidParentheses(const string& s) {
stack<int> stack;
int answer = 0;
for(int i=0;i<s.size();i++){
if(s[i]=='(') stack.push(i);
else{
if(!stack.empty() && s[stack.top()]=='('){
stack.pop();//stack.top存的是上一次s[i] (())
int last = -1;
if(!stack.empty()){
last = stack.top();
}
int curLen = i - last;
answer = max(curLen,answer);
}
else{
stack.push(i);
}
}
}
return answer;
}
};
两遍扫描 原因 如果一遍 (()这样的会出错,此时从后往前再扫描一次就行
class Solution {
public:
int longestValidParentheses(const string& s) {
int answer = 0, depth = 0, start = -1;
for (int i = 0; i < s.size(); ++i) {
if (s[i] == '(') {
++depth;
}
else {
--depth;
if (depth < 0) {
start = i;
depth = 0;
}
else if (depth == 0) {
answer = max(answer, i - start);
}
}
}
start = s.size();
depth = 0;
for(int i=s.size()-1;i>=0;i--){
if(s[i]==')')
depth++;
else{
depth--;
if(depth<0){
start = i;
depth = 0;
}
else if(depth==0){
answer = max(answer,start-i);
}
}
}
return answer;
}
};
DP的方法 我的弱点
int longestValidParentheses(string s) {
if(s.length() <= 1) return 0;
int curMax = 0;
vector<int> longest(s.size(),0);
for(int i=1; i < s.length(); i++){
if(s[i] == ')'){
if(s[i-1] == '('){
longest[i] = (i-2) >= 0 ? (longest[i-2] + 2) : 2;
curMax = max(longest[i],curMax);
}
else{ // if s[i-1] == ')', combine the previous length.
if(i-longest[i-1]-1 >= 0 && s[i-longest[i-1]-1] == '('){
longest[i] = longest[i-1] + 2 + ((i-longest[i-1]-2 >= 0)?longest[i-longest[i-1]-2]:0);
curMax = max(longest[i],curMax);
}
}
}
//else if s[i] == '(', skip it, because longest[i] must be 0
}
return curMax;
}