-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0020_valid_parentheses.html
More file actions
393 lines (338 loc) · 15 KB
/
0020_valid_parentheses.html
File metadata and controls
393 lines (338 loc) · 15 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LC 20: Valid Parentheses - Algorithm Visualization</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">#20</span> Valid Parentheses</h1>
<p>Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.</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/0020_valid_parentheses/0020_valid_parentheses.py</code>
</div>
</div>
<div class="explanation-panel">
<h4>🧠 How It Works (Layman's Terms)</h4>
<p>Think of stacking plates (LIFO - Last In, First Out):</p>
<ul>
<li><strong>Opening bracket:</strong> Push it onto the stack (like adding a plate)</li>
<li><strong>Closing bracket:</strong> Pop the top plate and check if it matches</li>
<li><strong>Mismatch:</strong> Wrong plate on top → Invalid!</li>
<li><strong>Empty stack when closing:</strong> Nothing to match → Invalid!</li>
<li><strong>Non-empty stack at end:</strong> Unclosed brackets → Invalid!</li>
</ul>
</div>
<div class="visualization-section">
<h3>🎬 Step-by-Step Visualization</h3>
<div class="controls">
<button class="btn btn-primary" id="stepBtn" onclick="step()">Step</button>
<button class="btn btn-success" id="autoBtn" onclick="toggleAuto()">Auto Run</button>
<button class="btn btn-warning" onclick="reset()">Reset</button>
</div>
<div class="status-message" id="statusMessage">
Click "Step" or "Auto Run" to start visualization
</div>
<div class="array-section">
<div class="array-label">📥 Input String:</div>
<div class="array-container" id="inputContainer"></div>
</div>
<div style="display: flex; gap: 30px; flex-wrap: wrap;">
<div class="array-section" style="flex: 1; min-width: 200px;">
<div class="array-label">📚 Stack:</div>
<div id="stackContainer" style="min-height: 200px; background: #f5f5f5; border-radius: 12px; border: 2px dashed #ccc; padding: 20px; display: flex; flex-direction: column-reverse; align-items: center; gap: 5px;">
<div style="color: #999;">Empty Stack</div>
</div>
</div>
<div class="array-section" style="flex: 1; min-width: 200px;">
<div class="array-label">🔗 Bracket Mapping:</div>
<div style="background: #f5f5f5; border-radius: 12px; padding: 20px;">
<div style="margin: 10px 0; font-size: 1.2em;"><span style="color: #f44336;">)</span> → <span style="color: #4caf50;">(</span></div>
<div style="margin: 10px 0; font-size: 1.2em;"><span style="color: #f44336;">]</span> → <span style="color: #4caf50;">[</span></div>
<div style="margin: 10px 0; font-size: 1.2em;"><span style="color: #f44336;">}</span> → <span style="color: #4caf50;">{</span></div>
</div>
</div>
</div>
<div class="info-box" id="resultBox" style="display: none; margin-top: 20px;">
Result will appear here
</div>
</div>
<div class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre>from typing import List
"""
LeetCode Valid Parentheses
Problem from LeetCode: https://leetcode.com/problems/valid-parentheses/
Description:
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', 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. Every close bracket has a corresponding open bracket of the same type.
Example 1:
Input: s = "()"
Output: true
Example 2:
Input: s = "()[]{}"
Output: true
Example 3:
Input: s = "(]"
Output: false
Example 4:
Input: s = "([)]"
Output: false
Example 5:
Input: s = "{[]}"
Output: true
"""
class Solution:
def is_valid(self, s: str) -> bool:
"""
Determine if a string of parentheses is valid.
Args:
s: String containing only parentheses characters
Returns:
bool: True if the string is valid, False otherwise
"""
# Initialize a stack to keep track of opening brackets
stack = []
# Define a mapping of closing brackets to their corresponding opening brackets
brackets_map = {
')': '(',
'}': '{',
']': '['
}
# Iterate through each character in the string
for char in s:
# If the character is a closing bracket
if char in brackets_map:
# Pop the top element from the stack if it's not empty, otherwise use a dummy value
top_element = stack.pop() if stack else '#'
# If the popped element doesn't match the corresponding opening bracket
if brackets_map[char] != top_element:
return False
# If the character is an opening bracket, push it onto the stack
else:
stack.append(char)
# If the stack is empty, all brackets were matched
return not stack
def is_valid_alternative(self, s: str) -> bool:
"""
Alternative implementation using a more direct approach.
Args:
s: String containing only parentheses characters
Returns:
bool: True if the string is valid, False otherwise
"""
stack = []
for char in s:
if char == '(' or char == '{' or char == '[':
stack.append(char)
else:
if not stack:
return False
if char == ')' and stack[-1] != '(':
return False
if char == '}' and stack[-1] != '{':
return False
if char == ']' and stack[-1] != '[':
return False
stack.pop()
return len(stack) == 0
if __name__ == '__main__':
# Example usage based on LeetCode sample
solution = Solution()
# Example 1
s1 = "()"
result1 = solution.is_valid(s1)
print(f"Example 1: '{s1}' -> {result1}") # Expected output: True
# Example 2
s2 = "()[]{}"
result2 = solution.is_valid(s2)
print(f"Example 2: '{s2}' -> {result2}") # Expected output: True
# Example 3
s3 = "(]"
result3 = solution.is_valid(s3)
print(f"Example 3: '{s3}' -> {result3}") # Expected output: False
# Example 4
s4 = "([)]"
result4 = solution.is_valid(s4)
print(f"Example 4: '{s4}' -> {result4}") # Expected output: False
# Example 5
s5 = "{[]}"
result5 = solution.is_valid(s5)
print(f"Example 5: '{s5}' -> {result5}") # Expected output: True
# Compare with alternative implementation
print("\nUsing alternative implementation:")
print(f"Example 1: '{s1}' -> {solution.is_valid_alternative(s1)}")
print(f"Example 3: '{s3}' -> {solution.is_valid_alternative(s3)}")
</pre>
</div>
</div>
</div>
<script>
const inputStr = "{[()]}";
const chars = inputStr.split('');
let stack = [];
let currentIndex = 0;
let autoInterval = null;
const bracketsMap = { ')': '(', '}': '{', ']': '[' };
const bracketColors = {
'(': '#4caf50', ')': '#4caf50',
'[': '#2196f3', ']': '#2196f3',
'{': '#ff9800', '}': '#ff9800'
};
function init() {
renderInput();
renderStack();
}
function renderInput() {
const container = document.getElementById('inputContainer');
container.innerHTML = '';
chars.forEach((char, idx) => {
const box = document.createElement('div');
box.className = 'array-box';
box.id = `input-${idx}`;
box.style.fontSize = '1.5em';
box.style.color = bracketColors[char] || '#333';
box.textContent = char;
if (idx < currentIndex) {
box.style.opacity = '0.5';
}
if (idx === currentIndex) {
box.classList.add('highlight');
}
container.appendChild(box);
});
}
function renderStack() {
const container = document.getElementById('stackContainer');
container.innerHTML = '';
if (stack.length === 0) {
container.innerHTML = '<div style="color: #999;">Empty Stack</div>';
return;
}
stack.forEach((item, idx) => {
const stackItem = document.createElement('div');
stackItem.style.cssText = `
width: 60px;
height: 50px;
display: flex;
justify-content: center;
align-items: center;
font-size: 1.8em;
font-weight: bold;
background: ${bracketColors[item]};
color: white;
border-radius: 8px;
box-shadow: 0 2px 5px rgba(0,0,0,0.2);
`;
stackItem.textContent = item;
stackItem.id = `stack-${idx}`;
container.appendChild(stackItem);
});
}
function step() {
if (currentIndex >= chars.length) {
// Check if stack is empty
if (stack.length === 0) {
document.getElementById('statusMessage').className = 'status-message success';
document.getElementById('statusMessage').textContent = 'Stack is empty - all brackets matched!';
document.getElementById('resultBox').style.display = 'block';
document.getElementById('resultBox').className = 'info-box secondary';
document.getElementById('resultBox').textContent = '✅ TRUE - Valid parentheses!';
} else {
document.getElementById('statusMessage').className = 'status-message error';
document.getElementById('statusMessage').textContent = `Stack not empty - ${stack.length} unclosed bracket(s)!`;
document.getElementById('resultBox').style.display = 'block';
document.getElementById('resultBox').className = 'info-box highlight';
document.getElementById('resultBox').textContent = '❌ FALSE - Invalid parentheses!';
}
document.getElementById('stepBtn').disabled = true;
stopAuto();
return;
}
const char = chars[currentIndex];
if (char in bracketsMap) {
// Closing bracket
if (stack.length === 0) {
document.getElementById('statusMessage').className = 'status-message error';
document.getElementById('statusMessage').textContent =
`'${char}' - No opening bracket to match!`;
document.getElementById('resultBox').style.display = 'block';
document.getElementById('resultBox').className = 'info-box highlight';
document.getElementById('resultBox').textContent = '❌ FALSE - Invalid parentheses!';
document.getElementById('stepBtn').disabled = true;
stopAuto();
return;
}
const top = stack.pop();
if (bracketsMap[char] !== top) {
document.getElementById('statusMessage').className = 'status-message error';
document.getElementById('statusMessage').textContent =
`'${char}' expects '${bracketsMap[char]}' but found '${top}'!`;
document.getElementById('resultBox').style.display = 'block';
document.getElementById('resultBox').className = 'info-box highlight';
document.getElementById('resultBox').textContent = '❌ FALSE - Invalid parentheses!';
document.getElementById('stepBtn').disabled = true;
stopAuto();
return;
}
document.getElementById('statusMessage').textContent =
`'${char}' matches '${top}' ✓ - Popped from stack`;
} else {
// Opening bracket
stack.push(char);
document.getElementById('statusMessage').textContent =
`'${char}' is opening bracket - Pushed to stack`;
}
currentIndex++;
renderInput();
renderStack();
}
function toggleAuto() {
if (autoInterval) {
stopAuto();
} else {
document.getElementById('autoBtn').textContent = 'Pause';
autoInterval = setInterval(() => {
if (currentIndex >= chars.length) {
step();
stopAuto();
} else {
step();
}
}, 800);
}
}
function stopAuto() {
if (autoInterval) {
clearInterval(autoInterval);
autoInterval = null;
}
document.getElementById('autoBtn').textContent = 'Auto Run';
}
function reset() {
stopAuto();
stack = [];
currentIndex = 0;
document.getElementById('stepBtn').disabled = false;
document.getElementById('statusMessage').className = 'status-message';
document.getElementById('statusMessage').textContent = 'Click "Step" or "Auto Run" to start visualization';
document.getElementById('resultBox').style.display = 'none';
init();
}
init();
</script>
</body>
</html>