32.longest-valid-parentheses.java 656 B

1234567891011121314151617181920212223
  1. import java.util.*;
  2. class Solution {
  3. public int longestValidParentheses(String s) {
  4. char[] chs = s.toCharArray();
  5. Stack<Integer> stack = new Stack<>();
  6. int max = 0, pre = -1;
  7. for (int i = 0; i < chs.length; i++) {
  8. char ch = chs[i];
  9. if (ch == '(') {
  10. stack.push(i);
  11. continue;
  12. } else if (stack.isEmpty()) {
  13. pre = i;
  14. continue;
  15. }
  16. stack.pop();
  17. if (stack.isEmpty()) max = Math.max(max, i - pre);
  18. else max = Math.max(max, i - stack.peek());
  19. }
  20. return max;
  21. }
  22. }