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