原文地址: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.
For "(()"
, the longest valid parentheses substring is "()"
, which has length = 2.
Another example is ")()())"
, where the longest valid parentheses substring is "()()"
, which has length = 4.
两种解法:
1.使用栈 O(n)和O(n)
栈用来记录 左括号的位置,遇到'(' 就将其位置下标入栈,遇到')',如果栈不空,就出栈,并且计算答案(两种情况,分出栈后栈为空和不为空);如果栈空,则设定一个变量记录最右边的')'。
class Solution {
public:
int longestValidParentheses(string s) {
int max_len = 0,last = -1;//the position of the last ')'
stack<int> lefts;// keep track of the positions of non-matching '('s
for(int i = 0;i<s.size();++i){
if(s[i]=='(')
{
lefts.push(i);
}
else{
if(lefts.empty()){
last=i;//no matching left
}
else{
//find a matching pair
lefts.pop();
if(lefts.empty()){
max_len = max(max_len,i-last);
}
else{
max_len=max(max_len,i-lefts.top());
}
}
}
}
return max_len;
}
};
2.两边遍历 O(n)和O(1)
直接用一个变量来记录最右边右括号的位置start,用一个变量depth来记录左括号的个数,遇到'(',就加1,遇到')', 就减1,如果这个变量为0了,那就计算长度,小于0了,就重新给赋值start。 但是一遍循环会出现得不到结果的情况,比如'(()',一遍遍历后,depth>0,没有结果,所以我们需要两次遍历,第二遍反过来遍历一遍,遇到')',depth++,依次类推。
代码:
class Solution {
public:
int longestValidParentheses(string s) {
int res = 0,depth = 0,start = -1;
for(int i = 0;i<s.length();++i){
if(s[i]=='(') depth++;
else{
depth--;
if(depth<0){
depth=0;
start = i;
}
else if(depth==0){
res = max(res,i-start);
}
}
}
depth = 0,start = s.length();
for(int i = s.length()-1;i>=0;--i){
if(s[i]==')') depth++;
else{
depth--;
if(depth<0){
depth=0;
start = i;
}
else if(depth==0){
res = max(res,start-i);
}
}
}
return res;
}
};