File tree Expand file tree Collapse file tree 1 file changed +18
-33
lines changed
src/main/java/com/fishercoder/solutions Expand file tree Collapse file tree 1 file changed +18
-33
lines changed Original file line number Diff line number Diff line change 2
2
3
3
import java .util .Stack ;
4
4
5
- /**
6
- * 32. Longest Valid Parentheses
7
- *
8
- * Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
9
- *
10
- * Example 1:
11
- * Input: "(()"
12
- * Output: 2
13
- * Explanation: The longest valid parentheses substring is "()"
14
- *
15
- * Example 2:
16
- * Input: ")()())"
17
- * Output: 4
18
- * Explanation: The longest valid parentheses substring is "()()"
19
- */
20
5
public class _32 {
21
- public static class Solution1 {
22
- public int longestValidParentheses (String s ) {
23
- int result = 0 ;
24
- Stack <Integer > stack = new Stack ();
25
- stack .push (-1 );
26
- for (int i = 0 ; i < s .length (); i ++) {
27
- if (s .charAt (i ) == '(' ) {
28
- stack .push (i );
29
- } else {
30
- stack .pop ();
31
- if (stack .isEmpty ()) {
32
- stack .push (i );
33
- } else {
34
- result = Math .max (result , i - stack .peek ());
35
- }
6
+ public static class Solution1 {
7
+ public int longestValidParentheses (String s ) {
8
+ int result = 0 ;
9
+ Stack <Integer > stack = new Stack ();
10
+ stack .push (-1 );
11
+ for (int i = 0 ; i < s .length (); i ++) {
12
+ if (s .charAt (i ) == '(' ) {
13
+ stack .push (i );
14
+ } else {
15
+ stack .pop ();
16
+ if (stack .isEmpty ()) {
17
+ stack .push (i );
18
+ } else {
19
+ result = Math .max (result , i - stack .peek ());
20
+ }
21
+ }
22
+ }
23
+ return result ;
36
24
}
37
- }
38
- return result ;
39
25
}
40
- }
41
26
}
You can’t perform that action at this time.
0 commit comments