-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0678_valid_parenthesis_string.html
More file actions
525 lines (452 loc) Β· 17.9 KB
/
0678_valid_parenthesis_string.html
File metadata and controls
525 lines (452 loc) Β· 17.9 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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Valid Parenthesis String - LeetCode 678</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">#0678</span> Valid Parenthesis String</h1>
<p><strong>Problem:</strong> Check if string with '(', ')', '*' can be valid. '*' can be '(', ')' or empty.</p>
<p><strong>Pattern:</strong> Greedy with Range - Track min/max possible open count</p>
<div class="problem-meta">
<span class="meta-tag">π€ String</span>
<span class="meta-tag">π Stack</span>
<span class="meta-tag">β±οΈ O(n)</span>
</div>
<div class="file-ref">
π Python: <code>python/0678_valid_parenthesis_string/0678_valid_parenthesis_string.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="visualization">
<svg id="mainSvg"></svg>
</div>
<div class="controls">
<button id="stepBtn">Step</button>
<button id="autoBtn">Auto Run</button>
<button id="resetBtn">Reset</button>
<div class="speed-control">
<label for="speed">Speed:</label>
<input type="range" id="speed" min="100" max="2000" value="800">
</div>
</div>
<div class="status" id="status">Click "Step" to validate string</div>
<div class="variables">
<div class="var-item">
<span class="var-label">Input:</span>
<span id="inputDisplay">"(*)"</span>
</div>
<div class="var-item">
<span class="var-label">Open Range (min, max):</span>
<span id="rangeDisplay">(0, 0)</span>
</div>
<div class="var-item">
<span class="var-label">Valid:</span>
<span id="resultDisplay">-</span>
</div>
</div>
</div>
<div class="code-section">
<h3>π» Python Solution</h3>
<div class="code-block">
<pre>from typing import List, Optional
"""
LeetCode Valid Parenthesis String
Problem from LeetCode: https://leetcode.com/problems/valid-parenthesis-string/
Description:
Given a string s containing only three types of characters: '(', ')' and '*', return true if s is valid.
The following rules define a valid string:
1. Any left parenthesis '(' must have a corresponding right parenthesis ')'.
2. Any right parenthesis ')' must have a corresponding left parenthesis '('.
3. Left parenthesis '(' must go before the corresponding right parenthesis ')'.
4. '*' could be treated as a single right parenthesis ')' or a single left parenthesis '(' or an empty string "".
Example 1:
Input: s = "()"
Output: true
Example 2:
Input: s = "(*)"
Output: true
Example 3:
Input: s = "(*))"
Output: true
Constraints:
1 <= s.length <= 100
s consists of characters '(', ')' and '*'.
"""
class Solution:
def check_valid_string(self, s: str) ->bool:
"""
Determine if the input string is valid.
An input string is valid if:
1. Open brackets must be closed by the same type of brackets.
2. Open brackets must be closed in the correct order.
3. '*' could be treated as a single right parenthesis ')' or a single left parenthesis '(' or an empty string "".
Args:
s: The input string containing only '(', ')' and '*'
Returns:
bool: True if the string is valid, False otherwise
"""
min_open = 0
max_open = 0
for char in s:
if char == '(':
min_open += 1
max_open += 1
elif char == ')':
min_open -= 1
max_open -= 1
else:
min_open -= 1
max_open += 1
if max_open < 0:
return False
min_open = max(min_open, 0)
return min_open == 0
def checkValidString_dp(self, s: str) ->bool:
"""
Alternative implementation using dynamic programming.
Args:
s: The input string containing only '(', ')' and '*'
Returns:
bool: True if the string is valid, False otherwise
"""
n = len(s)
if n == 0:
return True
dp = [([False] * n) for _ in range(n)]
for i in range(n):
if s[i] == '*':
dp[i][i] = True
for i in range(n - 1):
if (s[i] == '(' or s[i] == '*') and (s[i + 1] == ')' or s[i + 1
] == '*'):
dp[i][i + 1] = True
for length in range(3, n + 1):
for i in range(n - length + 1):
j = i + length - 1
if s[i] == '*' and dp[i + 1][j]:
dp[i][j] = True
continue
if (s[i] == '(' or s[i] == '*') and (s[j] == ')' or s[j] == '*'
):
if j - i == 1 or dp[i + 1][j - 1]:
dp[i][j] = True
continue
for k in range(i, j):
if dp[i][k] and dp[k + 1][j]:
dp[i][j] = True
break
return dp[0][n - 1]
def checkValidString_greedy(self, s: str) ->bool:
"""
Greedy approach with two passes to check for validity.
Args:
s: The input string containing only '(', ')' and '*'
Returns:
bool: True if the string is valid, False otherwise
"""
balance = 0
for char in s:
if char == '(' or char == '*':
balance += 1
else:
balance -= 1
if balance < 0:
return False
if balance == 0:
return True
balance = 0
for char in reversed(s):
if char == ')' or char == '*':
balance += 1
else:
balance -= 1
if balance < 0:
return False
return True
if __name__ == '__main__':
# Example usage based on LeetCode sample
solution = Solution()
# Example 1
s1 = "()"
result1 = solution.check_valid_string(s1)
print(f"Example 1: {result1}") # Expected: True
# Example 2
s2 = "(*)"
result2 = solution.check_valid_string(s2)
print(f"Example 2: {result2}") # Expected: True
# Example 3
s3 = "(*))"
result3 = solution.check_valid_string(s3)
print(f"Example 3: {result3}") # Expected: True
# Test with DP approach
print("\nWith DP approach:")
result4 = solution.checkValidString_dp(s3)
print(f"Example 3: {result4}") # Expected: True
# Test with greedy approach
print("\nWith greedy approach:")
result5 = solution.checkValidString_greedy(s3)
print(f"Example 3: {result5}") # Expected: True
</pre>
</div>
</div>
</div>
<script>
const s = "(*)";
let idx = 0;
let minOpen = 0, maxOpen = 0;
let isValid = null;
let autoRunning = false;
let autoTimer = null;
const width = 700;
const height = 400;
const svg = d3.select("#mainSvg")
.attr("width", width)
.attr("height", height);
const charWidth = 70;
const startX = (width - s.length * charWidth) / 2;
function draw() {
svg.selectAll("*").remove();
svg.append("text")
.attr("x", width / 2).attr("y", 25)
.attr("text-anchor", "middle")
.attr("font-weight", "bold")
.text(`Validating: "${s}"`);
// Draw string
for (let i = 0; i < s.length; i++) {
const x = startX + i * charWidth + charWidth / 2;
const y = 100;
let fill = "#e3f2fd", stroke = "#1976d2";
if (i < idx) {
fill = "#e0e0e0"; stroke = "#757575";
} else if (i === idx) {
fill = "#ffeb3b"; stroke = "#f57c00";
}
svg.append("rect")
.attr("x", x - 25).attr("y", y - 30)
.attr("width", 50).attr("height", 55)
.attr("rx", 8)
.attr("fill", fill).attr("stroke", stroke)
.attr("stroke-width", 2);
svg.append("text")
.attr("x", x).attr("y", y + 5)
.attr("text-anchor", "middle")
.attr("font-size", "32px")
.attr("font-weight", "bold")
.text(s[i]);
svg.append("text")
.attr("x", x).attr("y", y + 40)
.attr("text-anchor", "middle")
.attr("font-size", "12px")
.attr("fill", "#666")
.text(i);
}
// Current pointer
if (idx < s.length) {
svg.append("text")
.attr("x", startX + idx * charWidth + charWidth / 2)
.attr("y", 55)
.attr("text-anchor", "middle")
.attr("font-size", "16px")
.attr("fill", "#f57c00")
.text("βΌ");
}
// Range visualization
const rangeY = 220;
const rangeWidth = 300;
const rangeX = (width - rangeWidth) / 2;
const scale = rangeWidth / 8; // -2 to 6
svg.append("text")
.attr("x", width / 2).attr("y", 190)
.attr("text-anchor", "middle")
.attr("font-weight", "bold")
.text("Possible Open Paren Count Range");
// Axis
svg.append("line")
.attr("x1", rangeX).attr("y1", rangeY)
.attr("x2", rangeX + rangeWidth).attr("y2", rangeY)
.attr("stroke", "#333").attr("stroke-width", 2);
for (let i = -2; i <= 6; i++) {
const x = rangeX + (i + 2) * scale;
svg.append("line")
.attr("x1", x).attr("y1", rangeY - 5)
.attr("x2", x).attr("y2", rangeY + 5)
.attr("stroke", "#333");
svg.append("text")
.attr("x", x).attr("y", rangeY + 20)
.attr("text-anchor", "middle")
.attr("font-size", "12px")
.text(i);
}
// Range bar
const minX = rangeX + (Math.max(minOpen, -2) + 2) * scale;
const maxX = rangeX + (Math.min(maxOpen, 6) + 2) * scale;
if (maxOpen >= 0 && minOpen <= 6) {
svg.append("rect")
.attr("x", minX).attr("y", rangeY - 15)
.attr("width", Math.max(0, maxX - minX + 10))
.attr("height", 30)
.attr("rx", 5)
.attr("fill", "#c8e6c9").attr("stroke", "#4caf50")
.attr("opacity", 0.7);
// Min marker
svg.append("circle")
.attr("cx", minX).attr("cy", rangeY)
.attr("r", 8)
.attr("fill", "#4caf50");
svg.append("text")
.attr("x", minX).attr("y", rangeY - 25)
.attr("text-anchor", "middle")
.attr("font-size", "12px")
.attr("font-weight", "bold")
.text(`min=${minOpen}`);
// Max marker
svg.append("circle")
.attr("cx", maxX).attr("cy", rangeY)
.attr("r", 8)
.attr("fill", "#1976d2");
svg.append("text")
.attr("x", maxX).attr("y", rangeY + 40)
.attr("text-anchor", "middle")
.attr("font-size", "12px")
.attr("font-weight", "bold")
.text(`max=${maxOpen}`);
}
// Zero line
const zeroX = rangeX + 2 * scale;
svg.append("line")
.attr("x1", zeroX).attr("y1", rangeY - 25)
.attr("x2", zeroX).attr("y2", rangeY + 25)
.attr("stroke", "#e53935")
.attr("stroke-width", 2)
.attr("stroke-dasharray", "5,5");
// Explanation
svg.append("text")
.attr("x", 50).attr("y", 300)
.attr("font-size", "12px")
.text("'(' β min++, max++");
svg.append("text")
.attr("x", 50).attr("y", 320)
.attr("font-size", "12px")
.text("')' β min--, max--");
svg.append("text")
.attr("x", 50).attr("y", 340)
.attr("font-size", "12px")
.text("'*' β min-- (as ')'), max++ (as '(')");
// Result
if (isValid !== null) {
svg.append("rect")
.attr("x", width - 160).attr("y", height - 80)
.attr("width", 150).attr("height", 50)
.attr("rx", 10)
.attr("fill", isValid ? "#c8e6c9" : "#ffcdd2")
.attr("stroke", isValid ? "#4caf50" : "#e53935");
svg.append("text")
.attr("x", width - 85).attr("y", height - 48)
.attr("text-anchor", "middle")
.attr("font-size", "18px")
.attr("font-weight", "bold")
.text(isValid ? "β Valid!" : "β Invalid!");
}
}
function step() {
if (isValid !== null) {
draw();
return false;
}
if (idx >= s.length) {
isValid = minOpen === 0;
document.getElementById("resultDisplay").textContent =
isValid ? "Yes β" : "No β";
document.getElementById("status").textContent =
isValid ? `Valid! min_open = 0 at end.` :
`Invalid! min_open = ${minOpen} β 0`;
draw();
return false;
}
const c = s[idx];
let explanation = "";
if (c === '(') {
minOpen++;
maxOpen++;
explanation = `'(' β min=${minOpen}, max=${maxOpen}`;
} else if (c === ')') {
minOpen--;
maxOpen--;
explanation = `')' β min=${minOpen}, max=${maxOpen}`;
} else { // '*'
minOpen--;
maxOpen++;
explanation = `'*' β min=${minOpen} (as ')'), max=${maxOpen} (as '(')`;
}
if (maxOpen < 0) {
isValid = false;
document.getElementById("resultDisplay").textContent = "No β";
document.getElementById("status").textContent =
`Invalid! max_open < 0 means too many ')'`;
draw();
return false;
}
minOpen = Math.max(minOpen, 0);
document.getElementById("rangeDisplay").textContent =
`(${minOpen}, ${maxOpen})`;
document.getElementById("status").textContent = explanation;
idx++;
draw();
return idx < s.length;
}
function reset() {
idx = 0;
minOpen = 0;
maxOpen = 0;
isValid = null;
autoRunning = false;
if (autoTimer) clearInterval(autoTimer);
document.getElementById("rangeDisplay").textContent = "(0, 0)";
document.getElementById("resultDisplay").textContent = "-";
document.getElementById("status").textContent =
'Click "Step" to validate string';
document.getElementById("autoBtn").textContent = "Auto Run";
draw();
}
function autoRun() {
if (autoRunning) {
autoRunning = false;
clearInterval(autoTimer);
document.getElementById("autoBtn").textContent = "Auto Run";
} else {
autoRunning = true;
document.getElementById("autoBtn").textContent = "Pause";
const speed = 2100 - document.getElementById("speed").value;
autoTimer = setInterval(() => {
if (!step()) {
autoRunning = false;
clearInterval(autoTimer);
document.getElementById("autoBtn").textContent = "Auto Run";
}
}, speed);
}
}
document.getElementById("stepBtn").addEventListener("click", step);
document.getElementById("autoBtn").addEventListener("click", autoRun);
document.getElementById("resetBtn").addEventListener("click", reset);
draw();
</script>
</body>
</html>