Skip to content

Commit 3959e47

Browse files
refactor 32
1 parent 15af8a6 commit 3959e47

File tree

1 file changed

+18
-33
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+18
-33
lines changed

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

Lines changed: 18 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -2,40 +2,25 @@
22

33
import java.util.Stack;
44

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-
*/
205
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;
3624
}
37-
}
38-
return result;
3925
}
40-
}
4126
}

0 commit comments

Comments
 (0)