问题题目
32.最长有效括号
思路1 :暴力-栈模拟
class Solution {
public int longestValidParentheses(String s) {
Stack<Integer> stack = new Stack<>();
stack.push(-1);
int maxLen = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '(') {
stack.push(i);
} else {
stack.pop();
if (stack.isEmpty()) {
stack.push(i);
} else {
maxLen = Math.max(maxLen, i - stack.peek());
}
}
}
return maxLen;
}
}
思路2:动态规划
class Solution {
/*
.....(( X
.....()
.....))
.....)( X
*/
public int longestValidParentheses(String s) {
if(s.length() <= 1) return 0;
char[] chars = s.toCharArray();
//dp[i] means from s[0...i] 有效括号, 包含s[i]
int[