Skip to content

Commit 36d276d

Browse files
authored
Update readme with Longest Valid Parentheses solution
Added a detailed explanation and implementation for the Longest Valid Parentheses problem in Java.
1 parent bf2a2a5 commit 36d276d

File tree

1 file changed

+48
-1
lines changed
  • src/main/java/g0001_0100/s0032_longest_valid_parentheses

1 file changed

+48
-1
lines changed

src/main/java/g0001_0100/s0032_longest_valid_parentheses/readme.md

Lines changed: 48 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,4 +29,51 @@ Given a string containing just the characters `'('` and `')'`, return _the lengt
2929
**Constraints:**
3030

3131
* <code>0 <= s.length <= 3 * 10<sup>4</sup></code>
32-
* `s[i]` is `'('`, or `')'`.
32+
* `s[i]` is `'('`, or `')'`.
33+
34+
To solve the "Longest Valid Parentheses" problem in Java with a `Solution` class, we can follow these steps:
35+
36+
1. Define a `Solution` class.
37+
2. Define a method named `longestValidParentheses` that takes a string `s` as input and returns an integer representing the length of the longest valid parentheses substring.
38+
3. Initialize a stack to store the indices of characters.
39+
4. Initialize a variable `maxLen` to store the maximum length of valid parentheses found so far.
40+
5. Push `-1` onto the stack to mark the starting point of a potential valid substring.
41+
6. Iterate through each character of the string:
42+
- If the character is `'('`, push its index onto the stack.
43+
- If the character is `')'`:
44+
- Pop the top index from the stack.
45+
- If the stack is empty after popping, push the current index onto the stack to mark the starting point of the next potential valid substring.
46+
- Otherwise, update `maxLen` with the maximum of the current `maxLen` and `i - stack.peek()`, where `i` is the current index and `stack.peek()` is the index at the top of the stack.
47+
7. Return `maxLen`.
48+
49+
Here's the implementation:
50+
51+
```java
52+
import java.util.Stack;
53+
54+
public class Solution {
55+
public int longestValidParentheses(String s) {
56+
int maxLen = 0;
57+
Stack<Integer> stack = new Stack<>();
58+
stack.push(-1); // Mark the starting point of a potential valid substring
59+
60+
for (int i = 0; i < s.length(); i++) {
61+
char c = s.charAt(i);
62+
if (c == '(') {
63+
stack.push(i);
64+
} else { // c == ')'
65+
stack.pop();
66+
if (stack.isEmpty()) {
67+
stack.push(i); // Mark the starting point of the next potential valid substring
68+
} else {
69+
maxLen = Math.max(maxLen, i - stack.peek());
70+
}
71+
}
72+
}
73+
74+
return maxLen;
75+
}
76+
}
77+
```
78+
79+
This implementation provides a solution to the "Longest Valid Parentheses" problem in Java. It finds the length of the longest valid parentheses substring in the given string `s`.

0 commit comments

Comments
 (0)