-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0647_palindromic_substrings.html
More file actions
401 lines (342 loc) · 14.2 KB
/
0647_palindromic_substrings.html
File metadata and controls
401 lines (342 loc) · 14.2 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Palindromic Substrings - LeetCode 647</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">#0647</span> Palindromic Substrings</h1>
<p><strong>Problem:</strong> Count the number of palindromic substrings in a string.</p>
<p><strong>Pattern:</strong> Expand Around Center - Count palindromes expanding from each center</p>
<div class="problem-meta">
<span class="meta-tag">🌳 Tree</span>
<span class="meta-tag">🔤 String</span>
<span class="meta-tag">⏱️ O(n)</span>
</div>
<div class="file-ref">
📄 Python: <code>python/0647_palindromic_substrings/0647_palindromic_substrings.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 count palindromic substrings</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">Found Palindromes:</span>
<span id="foundDisplay">-</span>
</div>
<div class="var-item">
<span class="var-label">Total Count:</span>
<span id="countDisplay">0</span>
</div>
</div>
</div>
<div class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre>"""
647. Palindromic Substrings
https://leetcode.com/problems/palindromic-substrings/
Given a string s, return the number of palindromic substrings in it.
A string is a palindrome when it reads the same backward as forward.
A substring is a contiguous sequence of characters within the string.
Time Complexity: O(n²)
Space Complexity: O(1)
"""
class Solution:
def countSubstrings(self, s: str) -> int:
"""
Expand around each center approach.
For each position, expand outward checking for palindromes.
Consider both odd and even length palindromes.
"""
def countPalindromes(left: int, right: int) -> int:
count = 0
while left >= 0 and right < len(s) and s[left] == s[right]:
count += 1
left -= 1
right += 1
return count
total = 0
for i in range(len(s)):
# Odd length palindromes (single character center)
total += countPalindromes(i, i)
# Even length palindromes (between two characters)
total += countPalindromes(i, i + 1)
return total
def countSubstringsDP(self, s: str) -> int:
"""Alternative DP solution."""
n = len(s)
count = 0
# dp[i][j] = True if s[i:j+1] is palindrome
dp = [[False] * n for _ in range(n)]
# Single characters are palindromes
for i in range(n):
dp[i][i] = True
count += 1
# Check length 2
for i in range(n - 1):
if s[i] == s[i + 1]:
dp[i][i + 1] = True
count += 1
# Check length 3 and above
for length in range(3, n + 1):
for i in range(n - length + 1):
j = i + length - 1
if s[i] == s[j] and dp[i + 1][j - 1]:
dp[i][j] = True
count += 1
return count
# Test cases
if __name__ == "__main__":
solution = Solution()
# Test case 1
s1 = "abc"
print(f"Input: s='{s1}'")
print(f"Output: {solution.countSubstrings(s1)}") # 3 (a, b, c)
# Test case 2
s2 = "aaa"
print(f"Input: s='{s2}'")
print(f"Output: {solution.countSubstrings(s2)}") # 6 (a, a, a, aa, aa, aaa)
# Test case 3
s3 = "abba"
print(f"Input: s='{s3}'")
print(f"Output: {solution.countSubstrings(s3)}") # 6 (a, b, b, a, bb, abba)
</pre>
</div>
</div>
</div>
<script>
const s = "aaa";
let centerIdx = 0;
let isEven = false;
let left = 0, right = 0;
let expandPhase = 'start';
let count = 0;
let foundPalindromes = [];
let currentPalindromes = [];
let autoRunning = false;
let autoTimer = null;
const width = 700;
const height = 380;
const svg = d3.select("#mainSvg")
.attr("width", width)
.attr("height", height);
const charWidth = 80;
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(`Counting Palindromic Substrings in "${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 === left || i === right) {
fill = "#ffeb3b"; stroke = "#f57c00";
}
svg.append("rect")
.attr("x", x - 30).attr("y", y - 30)
.attr("width", 60).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);
}
// 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", 50)
.attr("text-anchor", "middle")
.attr("font-size", "14px")
.attr("fill", "#7b1fa2")
.text(isEven ? "▼ even" : "▼ odd");
}
// Found palindromes list
svg.append("text")
.attr("x", 50).attr("y", 200)
.attr("font-weight", "bold")
.text("Found Palindromes:");
const allFound = [...foundPalindromes, ...currentPalindromes];
const cols = 6;
allFound.forEach((p, i) => {
const col = i % cols;
const row = Math.floor(i / cols);
const isNew = i >= foundPalindromes.length;
svg.append("rect")
.attr("x", 50 + col * 90).attr("y", 210 + row * 30)
.attr("width", 80).attr("height", 25)
.attr("rx", 4)
.attr("fill", isNew ? "#fff3e0" : "#c8e6c9")
.attr("stroke", isNew ? "#ff9800" : "#4caf50");
svg.append("text")
.attr("x", 90 + col * 90).attr("y", 228 + row * 30)
.attr("text-anchor", "middle")
.attr("font-size", "14px")
.attr("font-weight", isNew ? "bold" : "normal")
.text(`"${p}"`);
});
// Count display
svg.append("rect")
.attr("x", width - 120).attr("y", 60)
.attr("width", 100).attr("height", 50)
.attr("rx", 10)
.attr("fill", "#e8eaf6").attr("stroke", "#3f51b5");
svg.append("text")
.attr("x", width - 70).attr("y", 82)
.attr("text-anchor", "middle")
.attr("font-size", "12px")
.text("Count:");
svg.append("text")
.attr("x", width - 70).attr("y", 102)
.attr("text-anchor", "middle")
.attr("font-size", "24px")
.attr("font-weight", "bold")
.attr("fill", "#3f51b5")
.text(count + currentPalindromes.length);
}
function step() {
if (centerIdx >= s.length && isEven) {
document.getElementById("status").textContent =
`Done! Total palindromic substrings: ${count}`;
draw();
return false;
}
if (expandPhase === 'start' || expandPhase === 'done') {
// Start new expansion
if (expandPhase === 'done') {
// Commit current palindromes
foundPalindromes.push(...currentPalindromes);
count += currentPalindromes.length;
currentPalindromes = [];
}
if (isEven) {
left = centerIdx;
right = centerIdx + 1;
} else {
left = centerIdx;
right = centerIdx;
}
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') {
if (left >= 0 && right < s.length && s[left] === s[right]) {
const palindrome = s.substring(left, right + 1);
currentPalindromes.push(palindrome);
document.getElementById("foundDisplay").textContent =
currentPalindromes.map(p => `"${p}"`).join(', ');
document.getElementById("status").textContent =
`Found palindrome: "${palindrome}"`;
left--;
right++;
} else {
expandPhase = 'done';
if (isEven) {
centerIdx++;
isEven = false;
} else {
isEven = true;
}
document.getElementById("countDisplay").textContent =
count + currentPalindromes.length;
document.getElementById("status").textContent =
`Expansion stopped. Found ${currentPalindromes.length} palindrome(s) from this center.`;
}
}
draw();
return centerIdx < s.length || !isEven;
}
function reset() {
centerIdx = 0;
isEven = false;
left = 0; right = 0;
expandPhase = 'start';
count = 0;
foundPalindromes = [];
currentPalindromes = [];
autoRunning = false;
if (autoTimer) clearInterval(autoTimer);
document.getElementById("centerDisplay").textContent = "-";
document.getElementById("foundDisplay").textContent = "-";
document.getElementById("countDisplay").textContent = "0";
document.getElementById("status").textContent =
'Click "Step" to count palindromic substrings';
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>