給定一個只包含 '(' 和 ')' 的字符串,找出最長的包含有效括號的子串的長度。
示例 1:
輸入: "(()"
輸出: 2
解釋: 最長有效括號子串爲 "()"
示例 2:
輸入: ")()())"
輸出: 4
解釋: 最長有效括號子串爲 "()()"
一看就是stack,注意首先push(-1)
class Solution {
public int longestValidParentheses(String s) {
int max = 0;
Stack<Integer> stack = new Stack<>();
stack.push(-1) ;
for(int i = 0; i < s.length();i++){
if(s.charAt(i) == '(')
stack.push(i);
else{
stack.pop();
if(stack.isEmpty())
stack.push(i);
else{
max = Math.max(i - stack.peek(),max);
}
}
}
return max;
}
}