dengxinyi 6 éve
szülő
commit
dcb636c71a
1 módosított fájl, 19 hozzáadás és 1 törlés
  1. 19 1
      hard/32.longest-valid-parentheses.java

+ 19 - 1
hard/32.longest-valid-parentheses.java

@@ -1,5 +1,23 @@
+import java.util.*;
+
 class Solution {
 class Solution {
     public int longestValidParentheses(String s) {
     public int longestValidParentheses(String s) {
-        
+        char[] chs = s.toCharArray();
+        Stack<Integer> stack = new Stack<>();
+        int max = 0, pre = -1;
+        for (int i = 0; i < chs.length; i++) {
+            if (chs[i] == '(') {
+                stack.push(i);
+                continue;
+            }
+            if (stack.empty()) {
+                pre = i;
+                continue;
+            }
+            stack.pop();
+            if (stack.empty()) max = Math.max(max, i - pre);
+            else max = Math.max(max, i - stack.peek());
+        }
+        return max;
     }
     }
 }
 }