-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0032_longest_valid_parentheses.html
More file actions
350 lines (292 loc) · 13.1 KB
/
0032_longest_valid_parentheses.html
File metadata and controls
350 lines (292 loc) · 13.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Longest Valid Parentheses - LeetCode 32</title>
<link rel="stylesheet" href="styles.css">
<script src="https://d3js.org/d3.v7.min.js"></script>
</head>
<body>
<div class="container">
<div class="problem-info">
<h1><span class="problem-number">#32</span> Longest Valid Parentheses</h1>
<p>Find the length of the longest valid (well-formed) parentheses substring.</p>
<div class="problem-meta">
<span class="meta-tag">String</span>
<span class="meta-tag">Stack</span>
<span class="meta-tag">Hard</span>
</div>
<div class="file-ref">
📄 Python: <code>python/0032_longest_valid_parentheses/0032_longest_valid_parentheses.py</code>
</div>
</div>
<div class="explanation-panel">
<h4>🧠 How It Works (Layman's Terms)</h4>
<p>A stack works like a <strong>pile of plates</strong> - last in, first out (LIFO):</p>
<ul>
<li><strong>Push:</strong> Add item to the top</li>
<li><strong>Pop:</strong> Remove and return the top item</li>
<li><strong>Peek:</strong> Look at top without removing</li>
<li><strong>Match pairs:</strong> Great for matching brackets, parentheses</li>
</ul>
</div>
<div class="visualization-section">
<h3>🎬 Step-by-Step Visualization</h3>
<div class="controls">
<button id="stepBtn">Step</button>
<button id="autoBtn">Auto Run</button>
<button id="resetBtn">Reset</button>
</div>
<svg id="mainSvg" width="800" height="380"></svg>
<div class="status-message" id="status">Click "Step" to find longest valid parentheses</div>
</div>
<div class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre>from typing import List
"""
LeetCode Longest Valid Parentheses
Problem from LeetCode: https://leetcode.com/problems/longest-valid-parentheses/
Description:
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
Example 1:
Input: s = "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()".
Example 2:
Input: s = ")()())"
Output: 4
Explanation: The longest valid parentheses substring is "()()".
Example 3:
Input: s = ""
Output: 0
"""
class Solution:
def longest_valid_parentheses(self, s: str) -> int:
"""
Find the length of the longest valid parentheses substring.
Uses a stack-based approach.
Args:
s: String containing only parentheses characters
Returns:
int: Length of the longest valid parentheses substring
"""
stack = [-1] # Initialize with -1 as a base index
max_length = 0
for i in range(len(s)):
if s[i] == '(':
stack.append(i)
else: # s[i] == ')'
stack.pop()
if not stack:
# No matching opening parenthesis, use current index as new base
stack.append(i)
else:
# Calculate length of current valid substring
max_length = max(max_length, i - stack[-1])
return max_length
def longest_valid_parentheses_dp(self, s: str) -> int:
"""
Find the length of the longest valid parentheses substring using dynamic programming.
Args:
s: String containing only parentheses characters
Returns:
int: Length of the longest valid parentheses substring
"""
if not s:
return 0
n = len(s)
# dp[i] represents the length of the longest valid substring ending at i
dp = [0] * n
max_length = 0
for i in range(1, n):
if s[i] == ')':
# Case 1: ()
if s[i-1] == '(':
dp[i] = (dp[i-2] if i >= 2 else 0) + 2
# Case 2: ))
elif i - dp[i-1] > 0 and s[i - dp[i-1] - 1] == '(':
dp[i] = dp[i-1] + 2
# Add any valid parentheses substring before this one
if i - dp[i-1] - 2 >= 0:
dp[i] += dp[i - dp[i-1] - 2]
max_length = max(max_length, dp[i])
return max_length
def longest_valid_parentheses_two_pass(self, s: str) -> int:
"""
Find the length of the longest valid parentheses substring using two passes.
Args:
s: String containing only parentheses characters
Returns:
int: Length of the longest valid parentheses substring
"""
max_length = 0
left = right = 0
# Left to right pass
for i in range(len(s)):
if s[i] == '(':
left += 1
else:
right += 1
if left == right:
max_length = max(max_length, 2 * right)
elif right > left:
# Invalid sequence, reset counters
left = right = 0
left = right = 0
# Right to left pass
for i in range(len(s) - 1, -1, -1):
if s[i] == ')':
right += 1
else:
left += 1
if left == right:
max_length = max(max_length, 2 * left)
elif left > right:
# Invalid sequence, reset counters
left = right = 0
return max_length
if __name__ == '__main__':
# Example usage based on LeetCode sample
solution = Solution()
# Example 1
s1 = "(()"
result1 = solution.longest_valid_parentheses(s1)
print(f"Example 1: s='{s1}', result={result1}") # Expected output: 2
# Example 2
s2 = ")()())"
result2 = solution.longest_valid_parentheses(s2)
print(f"Example 2: s='{s2}', result={result2}") # Expected output: 4
# Example 3
s3 = ""
result3 = solution.longest_valid_parentheses(s3)
print(f"Example 3: s='{s3}', result={result3}") # Expected output: 0
# Additional example
s4 = "()(())"
result4 = solution.longest_valid_parentheses(s4)
print(f"Example 4: s='{s4}', result={result4}") # Expected output: 6
# Compare with other implementations
print("\nUsing dynamic programming approach:")
print(f"Example 1: {solution.longest_valid_parentheses_dp(s1)}") # Expected output: 2
print(f"Example 2: {solution.longest_valid_parentheses_dp(s2)}") # Expected output: 4
print("\nUsing two-pass approach:")
print(f"Example 1: {solution.longest_valid_parentheses_two_pass(s1)}") # Expected output: 2
print(f"Example 2: {solution.longest_valid_parentheses_two_pass(s2)}") # Expected output: 4
</pre>
</div>
</div>
</div>
<script>
const s = ")()())";
let stack = [-1];
let maxLen = 0;
let i = 0;
let validRanges = [];
const width = 800, height = 380;
const svg = d3.select("#mainSvg");
let autoTimer = null, autoRunning = false;
function draw() {
svg.selectAll("*").remove();
const cellWidth = 50, startX = 150, startY = 80;
svg.append("text").attr("x", width/2).attr("y", 30)
.attr("text-anchor", "middle").attr("font-weight", "bold")
.text(`Finding Longest Valid Parentheses in "${s}"`);
// Draw string
for (let idx = 0; idx < s.length; idx++) {
const x = startX + idx * cellWidth;
let fill = "#e3f2fd", stroke = "#1976d2";
if (idx === i) { fill = "#fef3c7"; stroke = "#f59e0b"; }
// Check if in valid range
for (const range of validRanges) {
if (idx >= range.start && idx <= range.end) {
fill = "#d1fae5"; stroke = "#10b981";
}
}
svg.append("rect").attr("x", x).attr("y", startY)
.attr("width", cellWidth - 5).attr("height", 50)
.attr("rx", 8).attr("fill", fill).attr("stroke", stroke)
.attr("stroke-width", idx === i ? 3 : 2);
svg.append("text").attr("x", x + (cellWidth-5)/2).attr("y", startY + 33)
.attr("text-anchor", "middle").attr("font-size", "24px")
.attr("font-weight", "bold").text(s[idx]);
svg.append("text").attr("x", x + (cellWidth-5)/2).attr("y", startY + 65)
.attr("text-anchor", "middle").attr("font-size", "11px")
.attr("fill", "#666").text(idx);
}
// Stack visualization
svg.append("text").attr("x", 50).attr("y", 180).attr("font-weight", "bold").text("Stack:");
stack.forEach((val, idx) => {
svg.append("rect").attr("x", 110 + idx * 45).attr("y", 160)
.attr("width", 40).attr("height", 35).attr("rx", 5)
.attr("fill", "#e8f5e9").attr("stroke", "#4caf50");
svg.append("text").attr("x", 130 + idx * 45).attr("y", 183)
.attr("text-anchor", "middle").attr("font-weight", "bold").text(val);
});
// Max length
svg.append("rect").attr("x", 500).attr("y", 160)
.attr("width", 150).attr("height", 45).attr("rx", 10)
.attr("fill", "#e3f2fd").attr("stroke", "#1976d2");
svg.append("text").attr("x", 575).attr("y", 180)
.attr("text-anchor", "middle").attr("font-size", "12px").text("Max Length:");
svg.append("text").attr("x", 575).attr("y", 198)
.attr("text-anchor", "middle").attr("font-size", "20px")
.attr("font-weight", "bold").text(maxLen);
// Result
if (i >= s.length) {
svg.append("rect").attr("x", width/2 - 120).attr("y", 280)
.attr("width", 240).attr("height", 50).attr("rx", 12)
.attr("fill", "#d1fae5").attr("stroke", "#10b981").attr("stroke-width", 2);
svg.append("text").attr("x", width/2).attr("y", 312)
.attr("text-anchor", "middle").attr("font-size", "20px")
.attr("font-weight", "bold").attr("fill", "#10b981")
.text(`Answer: ${maxLen}`);
}
}
function step() {
if (i >= s.length) return false;
const char = s[i];
if (char === '(') {
stack.push(i);
document.getElementById("status").textContent = `'(' at index ${i}: Push ${i} to stack`;
} else {
stack.pop();
if (stack.length === 0) {
stack.push(i);
document.getElementById("status").textContent = `')' at index ${i}: Stack empty, push ${i} as new base`;
} else {
const len = i - stack[stack.length - 1];
if (len > maxLen) {
maxLen = len;
validRanges.push({start: stack[stack.length-1] + 1, end: i});
}
document.getElementById("status").textContent =
`')' at index ${i}: Valid length = ${i} - ${stack[stack.length-1]} = ${len}. Max = ${maxLen}`;
}
}
i++;
draw();
return i < s.length;
}
function reset() {
stack = [-1]; maxLen = 0; i = 0; validRanges = [];
if (autoTimer) clearInterval(autoTimer);
autoRunning = false;
document.getElementById("autoBtn").textContent = "Auto Run";
document.getElementById("status").textContent = 'Click "Step" to find longest valid parentheses';
draw();
}
function autoRun() {
if (autoRunning) { clearInterval(autoTimer); autoRunning = false; document.getElementById("autoBtn").textContent = "Auto Run"; }
else {
autoRunning = true; document.getElementById("autoBtn").textContent = "Pause";
autoTimer = setInterval(() => { if (!step()) { clearInterval(autoTimer); autoRunning = false; document.getElementById("autoBtn").textContent = "Auto Run"; } }, 800);
}
}
document.getElementById("stepBtn").addEventListener("click", step);
document.getElementById("autoBtn").addEventListener("click", autoRun);
document.getElementById("resetBtn").addEventListener("click", reset);
reset();
</script>
</body>
</html>