32.longest-valid-parentheses.java 633 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. if (chs[i] == '(') {
  9. stack.push(i);
  10. continue;
  11. }
  12. if (stack.empty()) {
  13. pre = i;
  14. continue;
  15. }
  16. stack.pop();
  17. if (stack.empty()) max = Math.max(max, i - pre);
  18. else max = Math.max(max, i - stack.peek());
  19. }
  20. return max;
  21. }
  22. }