原题链接: https://oj.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.
public class Solution {
public int longestValidParentheses(String s) {
Stack<Character> stack = new Stack<Character>();
int length = 0;
int maxLength = 0;
char c;
for(int i = 0; i < s.length(); i++){
c = s.charAt(i);
if(c == '(' ){
stack.push(c);
}
if(c == ')'){
if(stack.isEmpty()){
continue;
}
char d = stack.peek();
if(d == '(' && c!= ')') {
length = 0;
continue;
}
else {
stack.pop();
length = length + 2;
if(length > maxLength){
maxLength = length;
}
}
}
}
return maxLength;
}
}
但是这个是不对的。
Input: | "()(()" |
Output: | 4 |
Expected: | 2 |
Input: | "()(())" |
Output: | 4 |
Expected: | 6 |
为什么?
正确的代码:
方法I: 栈。Time O(n), Space O(n)
思路: “所有无法匹配的')'”的index其实都是各个group的分界点”
(引用:http://www.cnblogs.com/lichen782/p/leetcode_Longest_Valid_Parentheses.html)
public class Solution {
public int longestValidParentheses(String s) {
//code after reading dai's c++ code
//each ) is used to separate groups of valid parentheses
Stack<Integer> lefts = new Stack<Integer>();//store the indices of '('
int length = 0;
int maxLen = 0;
int last = -1;
char c;
for(int i = 0; i < s.length(); i++){
c = s.charAt(i);
if(c == '('){
lefts.push(i);
}
else{//c == ')'
if(lefts.isEmpty()){//this ) should be used as the separation point
last = i;
}
else{
lefts.pop();//match the current ) with previous ()
if(lefts.isEmpty()){//this group has completed
maxLen = Math.max(maxLen, i - last);
}
else{
maxLen = Math.max(maxLen, i - lefts.peek());
}
}
}
}
return maxLen;
}
}
方法II: DP 不懂。todo
方法III: 两边扫描。不懂为什么work. todo.