描述
给出一个只包含’(’ 和’)'的字符串,找出其中最长的左右括号正确匹配的合法子串。
样例
样例 1:
输入: "(()"
输出: 2
解释: 最长有效括号子串为 "()"
样例 2:
输入: ")()())"
输出: 4
解释: 最长有效括号子串为 "()()"
样例 3:
输入: "))(())()"
输出: 6
解释: 最长有效括号子串为 "(())()"
代码
public class Solution3 {
public static void main(String[] args) {
System.out.println(longestValidParentheses("))(())()"));
}
public static int longestValidParentheses(String s) {
// write your code here
char[] arr = s.toCharArray();
Stack<Integer> stack = new Stack<Integer>();
int len =arr.length,result = 0,startIdx = 0;
for (int i = 0; i < len; i++) {
if (arr[i] == '('){
stack.push(i);
}else{
if (stack.empty()){
startIdx =i+1;
}else{
int idx = stack.pop();
//result = result>i-idx?result:i-idx;
if (stack.empty()){
result = result>i-startIdx+1?result:i-startIdx+1;
}else{
result = result>(i-stack.peek())?result:i-stack.peek();
}
}
}
}
return result;
}
}