dengxinyi пре 6 година
родитељ
комит
dcb636c71a
1 измењених фајлова са 19 додато и 1 уклоњено
  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 {
     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;
     }
 }