Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
Example 1:
Input: "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()"
Example 2:
Input: ")()())"
Output: 4
Explanation: The longest valid parentheses substring is "()()"
Solution : stack
- 用stack记录括号的
index,但是记录哪些index呢?需要先推入-1进stack,为什么?继续看 - 先来看,如果stack中已经推入了左括号,当扫描到右括号的时候,我们就要把左括号弹出,此时就可以找到当前最大的长度,即
currentIndex - Stack.peek (). 为什么是Stack.peek ()? - 比如"()",首先将左括号的
index 0推入stack,stack此时变成:[-1, 0]. 然后扫描到右括号,发现stack peek是左括号可以匹配成有效对,所以弹出做括号,stack此时变成:[-1]。然后计算currentLen = 1 - (-1) ==> 2 - 是否只有左括号才推入
stack呢? 不是!!否则无法处理"())()()"这种有非法右括号的情况。
if (currentCh == ')' && tracker.peek () != -1 && s.charAt (tracker.peek ()) == '(') )
所以只要是不符合这个情况的,都要将其index推入stack. 这样每次求最大长度的时候,都能找到第一个左括号之前的那个index
class Solution {
public int longestValidParentheses(String s) {
if (s == null || s.length () < 2)
return 0;
int maxLen = 0;
Stack<Integer> tracker = new Stack<> ();
tracker.push (-1);
for (int index = 0; index < s.length (); index ++) {
char currentCh = s.charAt (index);
// if (currentCh == '(') {
// tracker.push (index);
// continue;
// }
// != -1: tracker is not empty, there is open parenthese there
if (currentCh == ')' &&
tracker.peek () != -1 &&
s.charAt (tracker.peek ()) == '(') {
tracker.pop ();
maxLen = Math.max (maxLen, index - tracker.peek ());
}
// 所有不满足配对条件的 都要推进去。不是只有"("才推。否则 ")()"这种情况就没法处理
else {
tracker.push (index);
}
}
return maxLen;
}
}










网友评论