-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0005_longest_palindromic_substring.html
More file actions
489 lines (417 loc) · 17.3 KB
/
Copy path0005_longest_palindromic_substring.html
File metadata and controls
489 lines (417 loc) · 17.3 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Longest Palindromic Substring - LeetCode 5</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">#0005</span> Longest Palindromic Substring</h1>
<p><strong>Problem:</strong> Find the longest palindromic substring in a given string.</p>
<p><strong>Pattern:</strong> Expand Around Center - For each position, expand outward while characters match</p>
<div class="problem-meta">
<span class="meta-tag">🌳 Tree</span>
<span class="meta-tag">🔤 String</span>
<span class="meta-tag">🧮 DP</span>
<span class="meta-tag">⏱️ O(n)</span>
</div>
<div class="file-ref">
📄 Python: <code>python/0005_longest_palindromic_substring/0005_longest_palindromic_substring.py</code>
</div>
</div>
<div class="explanation-panel">
<h4>🧠 How It Works (Layman's Terms)</h4>
<p>Tree traversal is like <strong>exploring a family tree</strong>:</p>
<ul>
<li><strong>Root:</strong> Start at the top node</li>
<li><strong>Recurse:</strong> Visit left and right children</li>
<li><strong>Base case:</strong> Stop at null/leaf nodes</li>
<li><strong>Combine:</strong> Build answer from subtree results</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 find longest palindrome</div>
<div class="variables">
<div class="var-item">
<span class="var-label">Center:</span>
<span id="centerDisplay">-</span>
</div>
<div class="var-item">
<span class="var-label">Current Palindrome:</span>
<span id="currentDisplay">-</span>
</div>
<div class="var-item">
<span class="var-label">Longest:</span>
<span id="longestDisplay">-</span>
</div>
</div>
</div>
<div class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre>from typing import List
"""
LeetCode Longest Palindromic Substring
Problem from LeetCode: https://leetcode.com/problems/longest-palindromic-substring/
Description:
Given a string s, return the longest palindromic substring in s.
A palindrome is a string that reads the same backward as forward.
Example 1:
Input: s = "babad"
Output: "bab"
Explanation: "aba" is also a valid answer.
Example 2:
Input: s = "cbbd"
Output: "bb"
Example 3:
Input: s = "a"
Output: "a"
"""
class Solution:
def longest_palindrome(self, s: str) -> str:
"""
Find the longest palindromic substring in a string.
Args:
s: Input string
Returns:
str: Longest palindromic substring
"""
if not s:
return ""
start = 0
max_length = 1
# Helper function to expand around center
def expand_around_center(left: int, right: int) -> int:
while left >= 0 and right < len(s) and s[left] == s[right]:
left -= 1
right += 1
return right - left - 1
for i in range(len(s)):
# Expand for odd length palindromes
odd_length = expand_around_center(i, i)
# Expand for even length palindromes
even_length = expand_around_center(i, i + 1)
# Find the maximum length palindrome
curr_length = max(odd_length, even_length)
if curr_length > max_length:
max_length = curr_length
# Calculate the starting position of the palindrome
start = i - (curr_length - 1) // 2
return s[start:start + max_length]
def longest_palindrome_dp(self, s: str) -> str:
"""
Find the longest palindromic substring using dynamic programming.
Args:
s: Input string
Returns:
str: Longest palindromic substring
"""
if not s:
return ""
n = len(s)
# dp[i][j] will be True if substring s[i:j+1] is a palindrome
dp = [[False for _ in range(n)] for _ in range(n)]
# All single characters are palindromes
for i in range(n):
dp[i][i] = True
start = 0
max_length = 1
# Check for palindromes of length 2
for i in range(n - 1):
if s[i] == s[i + 1]:
dp[i][i + 1] = True
start = i
max_length = 2
# Check for palindromes of length > 2
for length in range(3, n + 1):
for i in range(n - length + 1):
j = i + length - 1 # Ending index
# Check if s[i:j+1] is a palindrome
if s[i] == s[j] and dp[i + 1][j - 1]:
dp[i][j] = True
start = i
max_length = length
return s[start:start + max_length]
if __name__ == '__main__':
# Example usage based on LeetCode sample
solution = Solution()
# Example 1
s1 = "babad"
result1 = solution.longest_palindrome(s1)
print(f"Example 1: '{s1}' -> '{result1}'") # Expected output: "bab" or "aba"
# Example 2
s2 = "cbbd"
result2 = solution.longest_palindrome(s2)
print(f"Example 2: '{s2}' -> '{result2}'") # Expected output: "bb"
# Example 3
s3 = "a"
result3 = solution.longest_palindrome(s3)
print(f"Example 3: '{s3}' -> '{result3}'") # Expected output: "a"
# Compare with DP approach
print("\nUsing dynamic programming approach:")
result1_dp = solution.longest_palindrome_dp(s1)
print(f"Example 1 DP: '{s1}' -> '{result1_dp}'")
</pre>
</div>
</div>
</div>
<script>
const s = "babad";
let centerIdx = 0;
let isEven = false;
let left = 0, right = 0;
let expandPhase = 'start';
let longest = "";
let longestStart = -1, longestEnd = -1;
let currentStart = -1, currentEnd = -1;
let autoRunning = false;
let autoTimer = null;
const width = 750;
const height = 350;
const svg = d3.select("#mainSvg")
.attr("width", width)
.attr("height", height);
const charWidth = 60;
const startX = (width - s.length * charWidth) / 2;
function draw() {
svg.selectAll("*").remove();
svg.append("text")
.attr("x", width / 2).attr("y", 30)
.attr("text-anchor", "middle")
.attr("font-weight", "bold")
.text(`Finding Longest Palindromic Substring in "${s}"`);
// Draw string
for (let i = 0; i < s.length; i++) {
const x = startX + i * charWidth + charWidth / 2;
const y = 120;
// Background
let fill = "#e3f2fd", stroke = "#1976d2";
if (i >= longestStart && i <= longestEnd) {
fill = "#c8e6c9"; stroke = "#4caf50";
}
if (i >= currentStart && i <= currentEnd && expandPhase !== 'done') {
fill = "#fff3e0"; stroke = "#ff9800";
}
if (i === left || i === right) {
fill = "#ffeb3b"; stroke = "#f57c00";
}
svg.append("rect")
.attr("x", x - 25).attr("y", y - 30)
.attr("width", 50).attr("height", 50)
.attr("rx", 8)
.attr("fill", fill).attr("stroke", stroke)
.attr("stroke-width", 2);
svg.append("text")
.attr("x", x).attr("y", y)
.attr("text-anchor", "middle")
.attr("font-size", "28px")
.attr("font-weight", "bold")
.text(s[i]);
// Index
svg.append("text")
.attr("x", x).attr("y", y + 40)
.attr("text-anchor", "middle")
.attr("font-size", "12px")
.attr("fill", "#666")
.text(i);
}
// Center indicator
if (centerIdx < s.length) {
const centerX = startX + centerIdx * charWidth + charWidth / 2;
svg.append("text")
.attr("x", centerX + (isEven ? charWidth / 2 : 0))
.attr("y", 60)
.attr("text-anchor", "middle")
.attr("font-size", "14px")
.attr("fill", "#7b1fa2")
.text(isEven ? "▼ even center" : "▼ odd center");
}
// Left/Right pointers
if (expandPhase !== 'done' && expandPhase !== 'start') {
if (left >= 0 && left < s.length) {
svg.append("text")
.attr("x", startX + left * charWidth + charWidth / 2)
.attr("y", 185)
.attr("text-anchor", "middle")
.attr("font-size", "14px")
.attr("fill", "#f57c00")
.text("L");
}
if (right >= 0 && right < s.length) {
svg.append("text")
.attr("x", startX + right * charWidth + charWidth / 2)
.attr("y", 185)
.attr("text-anchor", "middle")
.attr("font-size", "14px")
.attr("fill", "#f57c00")
.text("R");
}
}
// Current and longest palindrome display
svg.append("text")
.attr("x", 50).attr("y", 250)
.attr("font-size", "14px")
.text("Current: ");
if (currentStart >= 0) {
svg.append("text")
.attr("x", 120).attr("y", 250)
.attr("font-size", "16px")
.attr("font-weight", "bold")
.attr("fill", "#ff9800")
.text(`"${s.substring(currentStart, currentEnd + 1)}"`);
}
svg.append("text")
.attr("x", 50).attr("y", 280)
.attr("font-size", "14px")
.text("Longest: ");
if (longest) {
svg.append("text")
.attr("x", 120).attr("y", 280)
.attr("font-size", "16px")
.attr("font-weight", "bold")
.attr("fill", "#4caf50")
.text(`"${longest}"`);
}
// Legend
const legend = [
{color: "#e3f2fd", label: "Unvisited"},
{color: "#ffeb3b", label: "L/R pointers"},
{color: "#fff3e0", label: "Current palindrome"},
{color: "#c8e6c9", label: "Longest found"}
];
legend.forEach((item, i) => {
svg.append("rect")
.attr("x", 10 + i * 140).attr("y", height - 30)
.attr("width", 15).attr("height", 15)
.attr("fill", item.color)
.attr("stroke", "#999");
svg.append("text")
.attr("x", 30 + i * 140).attr("y", height - 18)
.attr("font-size", "11px")
.text(item.label);
});
}
function step() {
if (centerIdx >= s.length && isEven) {
document.getElementById("status").textContent =
`Done! Longest palindrome: "${longest}"`;
draw();
return false;
}
if (expandPhase === 'start' || expandPhase === 'done') {
// Start new expansion
if (isEven) {
left = centerIdx;
right = centerIdx + 1;
} else {
left = centerIdx;
right = centerIdx;
}
currentStart = left;
currentEnd = right;
expandPhase = 'expanding';
document.getElementById("centerDisplay").textContent =
`${centerIdx}${isEven ? ' (even)' : ' (odd)'}`;
document.getElementById("status").textContent =
`Starting ${isEven ? 'even' : 'odd'} expansion from center ${centerIdx}`;
} else if (expandPhase === 'expanding') {
// Check if we can expand
if (left >= 0 && right < s.length && s[left] === s[right]) {
currentStart = left;
currentEnd = right;
document.getElementById("currentDisplay").textContent =
`"${s.substring(left, right + 1)}"`;
document.getElementById("status").textContent =
`s[${left}]='${s[left]}' == s[${right}]='${s[right]}' ✓ Expanding...`;
left--;
right++;
} else {
// Can't expand further
const current = s.substring(currentStart, currentEnd + 1);
if (current.length > longest.length) {
longest = current;
longestStart = currentStart;
longestEnd = currentEnd;
document.getElementById("longestDisplay").textContent =
`"${longest}" (len=${longest.length})`;
}
if (left < 0 || right >= s.length) {
document.getElementById("status").textContent =
`Reached boundary. Palindrome: "${current}"`;
} else {
document.getElementById("status").textContent =
`s[${left}]='${s[left]}' != s[${right}]='${s[right]}' ✗ Stop.`;
}
expandPhase = 'done';
// Move to next
if (isEven) {
centerIdx++;
isEven = false;
} else {
isEven = true;
}
}
}
draw();
return centerIdx < s.length || !isEven;
}
function reset() {
centerIdx = 0;
isEven = false;
left = 0; right = 0;
expandPhase = 'start';
longest = "";
longestStart = -1; longestEnd = -1;
currentStart = -1; currentEnd = -1;
autoRunning = false;
if (autoTimer) clearInterval(autoTimer);
document.getElementById("centerDisplay").textContent = "-";
document.getElementById("currentDisplay").textContent = "-";
document.getElementById("longestDisplay").textContent = "-";
document.getElementById("status").textContent =
'Click "Step" to find longest palindrome';
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>