用Stack的解法:
(1)遇到不匹配的,就把index入栈
(2)遇到匹配的,把匹配的pair清除,暴露出最靠近的没有匹配好的括号(中间可能清除多次)
所以栈顶保存的是没有匹配好的index0,index0到i中间的是匹配好的。
需要注意的是最开始要把-1压人栈中
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.
package l32;
import java.util.Stack;
public class Solution {
public int longestValidParentheses(String s) {
char[] cs = s.toCharArray();
int max = 0;
Stack<Integer> stack = new Stack<Integer>();
stack.push(-1);
for(int i=0; i<cs.length; i++) {
if(cs[i] == ')' && stack.size() > 1 && cs[stack.peek()] == '(') {
// match
stack.pop();
max = Math.max(max, i-stack.peek());
} else {
stack.push(i);
}
}
return max;
}
}