32. 最长有效括号
32. Longest Valid Parentheses
题目描述
给定一个只包含 '(' 和 ')' 的字符串,找出最长的包含有效括号的子串的长度。
每日一算法2019/6/3Day 31LeetCode32. Longest Valid Parentheses
示例 1:
输入: "(()"
输出: 2
解释: 最长有效括号子串为 "()"
输出: 2
解释: 最长有效括号子串为 "()"
示例 2:
输入: ")()())"
输出: 4
解释: 最长有效括号子串为 "()()"
输出: 4
解释: 最长有效括号子串为 "()()"
Java 实现
import java.util.Stack;
class Solution {
public int longestValidParentheses(String s) {
int res = 0,start = 0;
Stack<Integer> stack = new Stack<>();
for (int i=0;i<s.length();i++){
if (s.charAt(i) == '('){
stack.push(i);
}else if (s.charAt(i) == ')'){
if (stack.isEmpty()){
start = i +1;
}else {
stack.pop();
res = stack.isEmpty()?Math.max(res,i-start+1):Math.max(res,i-stack.peek());
}
}
}
return res;
}
}
相似题目
参考资料