Skip to content

Commit 1207a1e

Browse files
refactor 32
1 parent 3a7c262 commit 1207a1e

File tree

1 file changed

+24
-22
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+24
-22
lines changed

src/main/java/com/fishercoder/solutions/_32.java

Lines changed: 24 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -3,29 +3,31 @@
33
import java.util.Stack;
44

55
/**
6+
* 32. Longest Valid Parentheses
7+
*
68
* 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.
1111
*/
1212
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+
}
3133
}

0 commit comments

Comments
 (0)