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.
Have you met this question in a real interview?
思路: 首先, 凡是和括号有关的必须用 stack ,由于这个题要考虑断开的情况, 我们用一个 int 数组来存储 长度。
如果是左括号, 直接把index 存入stack, 如果是右括号, 而且stack 非空, 说明有可以匹配的左括号, 先获取做括号的位置, 然后这个有效长度为 i - pre + 1 , 但如果前面也是有效的, 就可以连接上了, 因此 判断 pre > 0 , 来加上 valid[pre - 1]
易错点: 1. 忘记可以连接的情况, 2。 判断 pre > 0 3.括号长度是 i - pre + 1 不是直接加2.
public class Solution {
public int longestValidParentheses(String s) {
int len = s.length();
if(len < 1)
return 0;
Stack<Integer> stack = new Stack<Integer>();
int[] valid = new int[len];//Storage the valid parentheses length
int max = 0;
int cur = 0;
for(int i = 0; i < len; i++){
if(s.charAt(i) == '(')
stack.push(i);
else{
if(!stack.isEmpty()){//-----
int pre = stack.pop();
valid[i] = i - pre + 1 + (pre > 0 ? valid[pre - 1] : 0);// 连接起来和前面的,防止()(()
max = Math.max(max, valid[i]);
}
}
}
return max;
}
}