题目:
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^2),再使用第20题中的方法判断它是否合法O(N),总时间为O(N^3)。
2.暴力解法
遍历一遍字符串O(N),从每个字符出发,累计左括号数和右括号数,并记录满足左括号数==右括号数时的各长度O(N),如果左括号数<右括号数了,continue。时间复杂度O(N^2)。
3.栈
用栈模拟匹配的过程,遍历一遍后,栈中剩下的即为匹配不上的括号,它们在字符串中的位置之间,即为符合要求的局部最长子串,从中取一个最长的。O(N)。
//C++
class Solution {
public:
int longestValidParentheses(string s) {
stack<int> st;
for (int i = 0; i < s.length(); i++)
if (s[i] == '(' || st.empty()) st.push(i);
else
if (s[st.top()] == '(') st.pop();
else st.push(i);
int left, right = s.length(),longest=0;
while (!st.empty()) {
left = st.top();
st.pop();
longest=max(longest,right-left-1);
right = left;
}
longest=max(longest,right);
return longest;
}
};
#Python
class Solution(object):
def longestValidParentheses(self, s):
"""
:type s: str
:rtype: int
"""
stack=[]
for i in xrange(len(s)):
if s[i]=='(' or not stack:
stack.append(i)
else:
t=stack.pop()
if s[t] == ')':
stack.append(t)
stack.append(i)
right,longest=len(s),0
while stack:
left=stack.pop()
longest=max(longest,right-left-1)
right=left
return max(longest,right)
4.栈改进版
我们发现在任一时刻,栈中存放的是之前的所有无法匹配的括号。那么当我们遇到一个’)’时,
如果栈顶是’(’:那么它们匹配成功,pop出’(‘后此时新的栈顶即最近的一个无法匹配的符号,我们只要用当前位置i - stack.top(),就能得到以当前位置符号为结尾的最长子串的长度。
如果栈顶是’)’:那么当前位置必然无法成为满足要求的子串的结尾(分析见栈改进版3.0),直接将‘)’入栈即可。
通过以上分析,我们能在一次遍历中同时处理栈和统计长度:
#Python
class Solution(object):
def longestValidParentheses(self, s):
"""
:type s: str
:rtype: int
"""
stack=[]
longest=0
for i in xrange(len(s)):
if s[i]=='(' or not stack:
stack.append(i)
else:
t=stack.pop()
if s[t]=='(':
if not stack:
left=-1
else:
left=stack[-1] # -1表示取最后一个
longest=max(longest,i-left)
else:
stack.append(t)
stack.append(i)
stack.append(i)
return longest
5.栈改进版2.0
我们可以在栈中预先放入一个-1,来减少代码:
#Python
class Solution(object):
def longestValidParentheses(self, s):
"""
:type s: str
:rtype: int
"""
stack=[-1]
longest=0
for i in xrange(len(s)):
if s[i]=='(' or not stack:
stack.append(i)
else:
t=stack.pop()
if t!=-1 and s[t]=='(':
longest=max(longest,i-stack[-1])
else:
stack.append(t)
stack.append(i)
return longest
6.栈改进版3.0
经过思考可以发现,不能匹配的符号肯定满足先是0个或若干个),再是0个或若干个( ,比如 )))(( 或者 )))或者 (( 。
也就是说有 ‘) ‘的话一定在最左边,’(’一定在最右边。
因此栈中只需要保存最后遇到的一个’)’即可。这里我们不妨假设-1位置处也存在一个’)’ 以减少代码
#Python 这是最快的版本了
class Solution(object):
def longestValidParentheses(self, s):
"""
:type s: str
:rtype: int
"""
stack = [-1]
max_length = 0
for i,p in enumerate(s):
if p == '(':
stack.append(i)
else:
stack.pop()
if not stack:
#因为有-1在的关系,如果弹出后栈为空,则弹出的一定不是'(',而是-1或')',就不需要像前面代码那样判断了
stack.append(i)
else:
length = i - stack[-1]
if max_length < length:
max_length = length
return max_length
7.正反两趟遍历
我们可能会这样想过:从左往右遍历一遍,累计左括号数和右括号数,并记录满足左括号数==右括号数时的各长度,如果左括号数<右括号数了,左右括号数置为0并继续(这里和方法2中直接continue不同)。
但是仅是这一遍是不够的,形如(()的结果是错误的。
通过前面的分析,我们可以知道对于不匹配的括号们,有 ) 的话一定在最左边,有(的话一定在最右边。
我们假设不匹配的括号们是)))((( , 那么这一趟下来其实)))部分都已经统计完成了,那么我们不妨反向再来一遍,处理(((部分:
从右往左遍历一遍,累计左括号数和右括号数,并记录满足左括号数==右括号数时的各长度,如果左括号数>右括号数了,左右括号数置为0并继续
//Java
public class Solution {
public int longestValidParentheses(String s) {
int left = 0, right = 0, maxlength = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') {
left++;
} else {
right++;
}
if (left == right) {
maxlength = Math.max(maxlength, 2 * right);
} else if (right >= left) {
left = right = 0;
}
}
left = right = 0;
for (int i = s.length() - 1; i >= 0; i--) {
if (s.charAt(i) == '(') {
left++;
} else {
right++;
}
if (left == right) {
maxlength = Math.max(maxlength, 2 * left);
} else if (left >= right) {
left = right = 0;
}
}
return maxlength;
}
}
8.DP
来自 https://leetcode.com/problems/longest-valid-parentheses/discuss/
My solution uses DP. The main idea is as follows: I construct a array longest[], for any longest[i], it stores the longest length of valid parentheses which is end at i.
And the DP idea is :
If s[i] is ‘(‘, set longest[i] to 0,because any string end with ‘(’ cannot be a valid one.
Else if s[i] is ‘)’
If s[i-1] is '(', longest[i] = longest[i-2] + 2
Else if s[i-1] is ')' and s[i-longest[i-1]-1] == '(', longest[i] = longest[i-1] + 2 + longest[i-longest[i-1]-2]
For example, input “()(())”, at i = 5, longest array is [0,2,0,0,2,0], longest[5] = longest[4] + 2 + longest[1] = 6.
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;
}
Updated: thanks to Philip0116, I have a more concise solution(though this is not as readable as the above one, but concise):
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] == ')' && 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);
}
}
return curMax;
}