-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0010_regular_expression_matching.html
More file actions
403 lines (346 loc) · 17.6 KB
/
0010_regular_expression_matching.html
File metadata and controls
403 lines (346 loc) · 17.6 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>010 - Regular Expression Matching</title>
<link rel="stylesheet" href="styles.css">
<script src="https://d3js.org/d3.v7.min.js"></script>
<style>
.string-display { display: flex; justify-content: center; gap: 5px; margin: 15px 0; flex-wrap: wrap; }
.char-box { width: 45px; height: 50px; display: flex; flex-direction: column; align-items: center; justify-content: center; border-radius: 8px; font-size: 1.2rem; font-weight: bold; transition: all 0.3s ease; }
.char-box.str { background: linear-gradient(135deg, #6366f1, #8b5cf6); color: white; }
.char-box.pattern { background: linear-gradient(135deg, #10b981, #34d399); color: white; }
.char-box.special { background: linear-gradient(135deg, #f59e0b, #ef4444); color: white; }
.char-box.current { box-shadow: 0 0 15px #f59e0b; border: 2px solid #f59e0b; }
.idx { font-size: 0.6rem; opacity: 0.7; margin-top: 3px; }
#dpTable { display: flex; justify-content: center; overflow-x: auto; padding: 10px; }
table { border-collapse: collapse; }
th, td { width: 45px; height: 45px; text-align: center; border: 1px solid #e2e8f0; font-size: 0.9rem; }
th { background: linear-gradient(135deg, #6366f1, #8b5cf6); color: white; }
td { background: #f8fafc; transition: all 0.3s ease; color: #334155; }
td.true { background: rgba(34, 197, 94, 0.3); color: #166534; font-weight: bold; }
td.false { background: rgba(239, 68, 68, 0.1); color: #94a3b8; }
td.current { box-shadow: inset 0 0 10px #f59e0b; border: 2px solid #f59e0b; }
.legend { display: flex; justify-content: center; gap: 20px; margin-top: 15px; flex-wrap: wrap; }
.legend-item { display: flex; align-items: center; gap: 8px; font-size: 0.85rem; color: #64748b; }
.legend-color { width: 20px; height: 20px; border-radius: 4px; }
.result { font-size: 1.5rem; text-align: center; padding: 20px; border-radius: 8px; margin-top: 15px; }
.result.match { background: rgba(34, 197, 94, 0.2); border: 2px solid #22c55e; color: #166534; }
.result.nomatch { background: rgba(239, 68, 68, 0.2); border: 2px solid #ef4444; color: #dc2626; }
input { background: #f8fafc; color: #334155; border: 1px solid #e2e8f0; padding: 10px; border-radius: 8px; font-size: 0.9rem; width: 120px; }
input:focus { outline: none; border-color: #6366f1; }
.info-box { background: #f1f5f9; border-radius: 8px; padding: 15px; margin-bottom: 15px; font-size: 0.9rem; line-height: 1.6; color: #475569; }
</style>
</head>
<body>
<div class="container">
<section class="problem-info">
<h1><span class="problem-number">#10</span> Regular Expression Matching</h1>
<p>Implement regular expression matching with support for '.' and '*'. '.' matches any single character, '*' matches zero or more of the preceding element.</p>
<div class="problem-meta">
<span class="meta-tag">Hard</span>
<span class="meta-tag">Dynamic Programming</span>
<span class="meta-tag">String</span>
</div>
<div class="file-ref">
📄 Python: <code>python/0010_regular_expression_matching/0010_regular_expression_matching.py</code>
</div>
</section>
<div class="explanation-panel">
<h4>🧠 How It Works (Layman's Terms)</h4>
<p>This algorithm solves the problem <strong>step by step</strong>:</p>
<ul>
<li><strong>Understand:</strong> Parse the input data</li>
<li><strong>Process:</strong> Apply the core logic</li>
<li><strong>Optimize:</strong> Use efficient data structures</li>
<li><strong>Return:</strong> Output the computed result</li>
</ul>
</div>
<section class="visualization-section">
<h3>🎬 Step-by-Step Visualization</h3>
<div class="controls">
<label>String: <input type="text" id="strInput" value="aab"></label>
<label>Pattern: <input type="text" id="patternInput" value="c*a*b"></label>
<button onclick="setInputs()">Set</button>
<button id="stepBtn" onclick="step()">Step</button>
<button id="autoBtn" onclick="toggleAuto()">▶ Auto Run</button>
<button onclick="reset()">Reset</button>
</div>
</section>
<section class="visualization-section">
<h3>🎬 Step-by-Step Visualization</h3>
<div class="info-box">
<strong>'.'</strong> matches any single character. <strong>'*'</strong> matches zero or more of the preceding element.
</div>
<div>
<div style="text-align: center; margin-bottom: 5px; color: #64748b;">String s:</div>
<div class="string-display" id="strDisplay"></div>
</div>
<div style="margin-top: 15px;">
<div style="text-align: center; margin-bottom: 5px; color: #64748b;">Pattern p:</div>
<div class="string-display" id="patternDisplay"></div>
</div>
</section>
<section class="visualization-section">
<h3>🎬 Step-by-Step Visualization</h3>
<div id="dpTable"></div>
<div class="legend">
<div class="legend-item"><div class="legend-color" style="background: rgba(34, 197, 94, 0.3);"></div> True (Match)</div>
<div class="legend-item"><div class="legend-color" style="background: rgba(239, 68, 68, 0.1);"></div> False (No Match)</div>
<div class="legend-item"><div class="legend-color" style="background: rgba(251, 191, 36, 0.3);"></div> Currently Processing</div>
</div>
<div class="status-message" id="stepDisplay">Ready to start</div>
<div id="resultArea"></div>
</section>
<section class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre>from typing import List
"""
LeetCode Regular Expression Matching
Problem from LeetCode: https://leetcode.com/problems/regular-expression-matching/
Description:
Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where:
- '.' Matches any single character.
- '*' Matches zero or more of the preceding element.
The matching should cover the entire input string (not partial).
Example 1:
Input: s = "aa", p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".
Example 2:
Input: s = "aa", p = "a*"
Output: true
Explanation: '*' means zero or more of the preceding element, 'a'. Therefore, by repeating 'a' once, it becomes "aa".
Example 3:
Input: s = "ab", p = ".*"
Output: true
Explanation: ".*" means "zero or more (*) of any character (.)".
"""
class Solution:
def is_match(self, s: str, p: str) -> bool:
"""
Check if a string matches a pattern with '.' and '*' wildcard characters.
Args:
s: Input string
p: Pattern string with '.' and '*'
Returns:
bool: True if the string matches the pattern, False otherwise
"""
# Create a memoization cache
memo = {}
def dp(i, j):
# If we've seen this state before, return the cached result
if (i, j) in memo:
return memo[(i, j)]
# If pattern is exhausted, string must also be exhausted
if j == len(p):
return i == len(s)
# Check if the current characters match
first_match = i < len(s) and (p[j] == s[i] or p[j] == '.')
# If the next pattern character is '*'
if j + 1 < len(p) and p[j + 1] == '*':
# Two options:
# 1. Skip the pattern element with '*' (use zero occurrences)
# 2. Use the pattern element if it matches, and then try again from the next string position
memo[(i, j)] = dp(i, j + 2) or (first_match and dp(i + 1, j))
return memo[(i, j)]
# Without '*', must match current character and proceed
memo[(i, j)] = first_match and dp(i + 1, j + 1)
return memo[(i, j)]
return dp(0, 0)
def is_match_bottom_up(self, s: str, p: str) -> bool:
"""
Check if a string matches a pattern using bottom-up dynamic programming.
Args:
s: Input string
p: Pattern string with '.' and '*'
Returns:
bool: True if the string matches the pattern, False otherwise
"""
# dp[i][j] represents if s[0:i] matches p[0:j]
dp = [[False for _ in range(len(p) + 1)] for _ in range(len(s) + 1)]
# Empty pattern matches empty string
dp[0][0] = True
# Handle patterns like a*, a*b*, a*b*c* matching empty string
for j in range(1, len(p) + 1):
if p[j-1] == '*':
dp[0][j] = dp[0][j-2]
for i in range(1, len(s) + 1):
for j in range(1, len(p) + 1):
if p[j-1] == '*':
# If we consider zero occurrences of the preceding element
dp[i][j] = dp[i][j-2]
# If the pattern character before '*' matches the current string character
if p[j-2] == '.' or p[j-2] == s[i-1]:
dp[i][j] = dp[i][j] or dp[i-1][j]
elif p[j-1] == '.' or p[j-1] == s[i-1]:
dp[i][j] = dp[i-1][j-1]
return dp[len(s)][len(p)]
if __name__ == '__main__':
# Example usage based on LeetCode sample
solution = Solution()
# Example 1
s1, p1 = "aa", "a"
result1 = solution.is_match(s1, p1)
print(f"Example 1: s='{s1}', p='{p1}' -> {result1}") # Expected output: False
# Example 2
s2, p2 = "aa", "a*"
result2 = solution.is_match(s2, p2)
print(f"Example 2: s='{s2}', p='{p2}' -> {result2}") # Expected output: True
# Example 3
s3, p3 = "ab", ".*"
result3 = solution.is_match(s3, p3)
print(f"Example 3: s='{s3}', p='{p3}' -> {result3}") # Expected output: True
# Additional examples
s4, p4 = "aab", "c*a*b"
result4 = solution.is_match(s4, p4)
print(f"Example 4: s='{s4}', p='{p4}' -> {result4}") # Expected output: True
# Compare with bottom-up approach
print("\nUsing bottom-up dynamic programming:")
print(f"Example 1: {solution.is_match_bottom_up(s1, p1)}")
print(f"Example 2: {solution.is_match_bottom_up(s2, p2)}")
print(f"Example 3: {solution.is_match_bottom_up(s3, p3)}")
</pre>
</div>
</section>
</div>
<script>
let s = "aab";
let p = "c*a*b";
let dp = [];
let steps = [];
let stepIndex = 0;
let autoInterval = null;
let isComplete = false;
function setInputs() {
s = document.getElementById('strInput').value;
p = document.getElementById('patternInput').value;
reset();
}
function reset() {
const m = s.length, n = p.length;
dp = Array(m + 1).fill(null).map(() => Array(n + 1).fill(false));
steps = [];
stepIndex = 0;
isComplete = false;
if (autoInterval) {
clearInterval(autoInterval);
autoInterval = null;
document.getElementById('autoBtn').textContent = '▶ Auto Run';
}
steps.push({ i: 0, j: 0, value: true, desc: "Empty pattern matches empty string" });
for (let j = 2; j <= n; j++) {
if (p[j-1] === '*') {
steps.push({ i: 0, j: j, value: true, checkJ: j-2, desc: `Pattern "${p.substring(0,j)}" can match empty string (skip ${p[j-2]}*)` });
}
}
for (let i = 1; i <= m; i++) {
for (let j = 1; j <= n; j++) {
if (p[j-1] === '*') {
let zeroMatch = false;
if (j >= 2) zeroMatch = steps.find(st => st.i === i && st.j === j-2)?.value || false;
let oneMore = false;
if (j >= 2 && (p[j-2] === '.' || p[j-2] === s[i-1])) {
oneMore = steps.find(st => st.i === i-1 && st.j === j)?.value || false;
}
const val = zeroMatch || oneMore;
let desc = `'*': Zero occur (dp[${i}][${j-2}]=${zeroMatch})`;
if (j >= 2 && (p[j-2] === '.' || p[j-2] === s[i-1])) {
desc += ` OR one+ (dp[${i-1}][${j}]=${oneMore})`;
}
steps.push({ i, j, value: val, desc });
} else if (p[j-1] === '.' || p[j-1] === s[i-1]) {
const prev = steps.find(st => st.i === i-1 && st.j === j-1)?.value || false;
steps.push({ i, j, value: prev, desc: `'${p[j-1]}' matches '${s[i-1]}': dp[${i-1}][${j-1}]=${prev}` });
} else {
steps.push({ i, j, value: false, desc: `'${p[j-1]}' ≠ '${s[i-1]}': no match` });
}
}
}
render();
}
function step() {
if (isComplete || stepIndex >= steps.length) {
isComplete = true;
render();
return;
}
const st = steps[stepIndex];
dp[st.i][st.j] = st.value;
stepIndex++;
render();
}
function toggleAuto() {
if (autoInterval) {
clearInterval(autoInterval);
autoInterval = null;
document.getElementById('autoBtn').textContent = '▶ Auto Run';
} else {
autoInterval = setInterval(() => {
if (stepIndex >= steps.length) {
clearInterval(autoInterval);
autoInterval = null;
document.getElementById('autoBtn').textContent = '▶ Auto Run';
isComplete = true;
render();
} else {
step();
}
}, 500);
document.getElementById('autoBtn').textContent = '⏸ Pause';
}
}
function render() {
const m = s.length, n = p.length;
let strHtml = '<div class="char-box str" style="background: #94a3b8;"><span>ε</span><span class="idx">0</span></div>';
for (let i = 0; i < s.length; i++) {
strHtml += `<div class="char-box str"><span>${s[i]}</span><span class="idx">${i+1}</span></div>`;
}
document.getElementById('strDisplay').innerHTML = strHtml;
let patHtml = '<div class="char-box pattern" style="background: #94a3b8;"><span>ε</span><span class="idx">0</span></div>';
for (let j = 0; j < p.length; j++) {
const isSpecial = p[j] === '.' || p[j] === '*';
patHtml += `<div class="char-box ${isSpecial ? 'special' : 'pattern'}"><span>${p[j]}</span><span class="idx">${j+1}</span></div>`;
}
document.getElementById('patternDisplay').innerHTML = patHtml;
let tableHtml = '<table><tr><th></th><th>ε</th>';
for (let j = 0; j < n; j++) tableHtml += `<th>${p[j]}</th>`;
tableHtml += '</tr>';
for (let i = 0; i <= m; i++) {
tableHtml += `<tr><th>${i === 0 ? 'ε' : s[i-1]}</th>`;
for (let j = 0; j <= n; j++) {
const isCurrent = stepIndex > 0 && stepIndex <= steps.length &&
steps[stepIndex-1].i === i && steps[stepIndex-1].j === j;
const cellClass = isCurrent ? 'current' : (dp[i][j] ? 'true' : 'false');
tableHtml += `<td class="${cellClass}">${dp[i][j] ? 'T' : 'F'}</td>`;
}
tableHtml += '</tr>';
}
tableHtml += '</table>';
document.getElementById('dpTable').innerHTML = tableHtml;
const stepDisplay = document.getElementById('stepDisplay');
if (stepIndex > 0 && stepIndex <= steps.length) {
const st = steps[stepIndex - 1];
stepDisplay.textContent = `dp[${st.i}][${st.j}] = ${st.value}: ${st.desc}`;
} else if (isComplete) {
stepDisplay.textContent = `Complete!`;
} else {
stepDisplay.textContent = 'Ready to start';
}
stepDisplay.className = 'status-message';
if (isComplete) {
const match = dp[m][n];
document.getElementById('resultArea').innerHTML = `
<div class="result ${match ? 'match' : 'nomatch'}">
${match ? '✅ Pattern matches!' : '❌ No match'}
</div>`;
} else {
document.getElementById('resultArea').innerHTML = '';
}
}
reset();
</script>
</body>
</html>