参照这个代码改的,运用了dp
https://leetcode.com/problems/longest-valid-parentheses/discuss/353653/Pure-python-DP
class Solution {
public int longestValidParentheses(String s) {
int[] mem = new int[s.length()];
int max = 0;
for(int i = 0; i < s.length(); ++i){
if(s.charAt(i) == ')'){
if((i - 1) >= 0 && i - mem[i - 1] - 1 >= 0 && s.charAt(i - mem[i - 1] - 1) == '('){
int temp = 2 + mem[i - 1];
if((i - 2 - mem[i - 1]) >= 0){
temp += mem[i - 2 - mem[i - 1]];
}
mem[i] = temp;
max = Math.max(max, temp);
}
}
}
return max;
}
}