classSolution{ publicintlongestValidParentheses(String s){ if (s.length() < 2) return0; Stack<Integer> st = new Stack<>(); int res = 0; for (int i = 0; i < s.length(); i++){ if (s.charAt(i) == '('){ st.push(i); } else{ if (st.isEmpty()){ st.push(i); } else { if (s.charAt(st.peek()) == '('){ st.pop(); res = Math.max(res, i - (st.isEmpty() ? -1 : st.peek())); } else{ st.push(i); } } } } return res; } }
Solution 2: DP
1 2 3 4 5 6 7
If s[i] is '(', set dp[i] to 0,because any string end with '(' cannot be a valid one.
Else if s[i] is ')'
If s[i-1] is '(', dp[i] = dp[i-2] + 2
Else if s[i-1] is ')' and s[i-dp[i-1]-1] == '(', dp[i] = dp[i-1] + 2 + dp[i-dp[i-1]-2]