-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0271_encode_and_decode_strings.html
More file actions
430 lines (367 loc) · 16.1 KB
/
0271_encode_and_decode_strings.html
File metadata and controls
430 lines (367 loc) · 16.1 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Encode and Decode Strings - LeetCode 271</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">#271</span> Encode and Decode Strings</h1>
<p>Design an algorithm to encode a list of strings to a single string, then decode it back. The trick is handling strings that may contain any character, including delimiters!</p>
<div class="problem-meta">
<span class="meta-tag">📁 Array & Hashing</span>
<span class="meta-tag">🔤 String Encoding</span>
<span class="meta-tag">⏱️ O(n)</span>
</div>
<div class="file-ref">
📄 Python: <a href="../python/0271_encode_and_decode_strings/0271_encode_and_decode_strings.py">0271_encode_and_decode_strings.py</a>
</div>
</div>
<div class="explanation-panel">
<h4>💡 How It Works (Layman's Terms)</h4>
<ul>
<li><strong>Problem:</strong> How do you combine multiple strings into one, then split them back? You can't just use a comma—what if a string contains a comma?</li>
<li><strong>Solution:</strong> Before each string, write its length followed by #. Like "5#Hello5#World"</li>
<li><strong>Encoding:</strong> For each string, prepend "[length]#" so we know exactly how many characters to read</li>
<li><strong>Decoding:</strong> Read until #, get the length, read that many characters, repeat</li>
<li><strong>Why it works:</strong> Even if a string contains "#" or numbers, we always know exactly how many characters belong to each string</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="phase-indicator">
<div class="phase-box" id="encodePhase">
<div class="phase-title">Encoding</div>
<div class="phase-description">Build "length#string"</div>
</div>
<div class="phase-box" id="decodePhase">
<div class="phase-title">Decoding</div>
<div class="phase-description">Parse back to list</div>
</div>
</div>
<div class="status-message" id="statusMessage">
Click "Step" or "Auto Run" to visualize encode/decode process
</div>
<div class="array-section">
<div class="array-label">Input Strings:</div>
<div class="array-container" id="inputContainer"></div>
</div>
<div class="array-section">
<div class="array-label">Encoded String:</div>
<div id="encodedContainer" style="font-family: monospace; font-size: 1.4em; background: #f5f5f5; padding: 15px; border-radius: 10px; word-break: break-all;"></div>
</div>
<div class="array-section">
<div class="array-label">Decoded Result:</div>
<div class="array-container" id="decodedContainer"></div>
</div>
</div>
<div class="code-section">
<h3>💻 Python Solution - Length Prefix Encoding</h3>
<div class="code-block">
<pre>from typing import List
"""
LeetCode 271. Encode and Decode Strings
Problem from LeetCode: https://leetcode.com/problems/encode-and-decode-strings/
Description:
Design an algorithm to encode a list of strings to a string. The encoded string is then sent over the network and is decoded back to the original list of strings.
Machine 1 (sender) has the function:
string encode(vector<string> strs) {
// ... your code
return encoded_string;
}
Machine 2 (receiver) has the function:
vector<string> decode(string s) {
//... your code
return strs;
}
So Machine 1 does:
string encoded_string = encode(strs);
and Machine 2 does:
vector<string> strs2 = decode(encoded_string);
strs2 in Machine 2 should be the same as strs in Machine 1.
Implement the encode and decode methods.
You are not allowed to solve the problem using any serialize methods (such as eval).
Example 1:
Input: dummy_input = ["Hello","World"]
Output: ["Hello","World"]
Explanation:
Machine 1:
Codec encoder = new Codec();
String msg = encoder.encode(strs);
Machine 1 ---msg---> Machine 2
Machine 2:
Codec decoder = new Codec();
String[] strs = decoder.decode(msg);
Example 2:
Input: dummy_input = [""]
Output: [""]
"""
class Codec:
"""
Design an algorithm to encode a list of strings to a string.
The encoded string is then sent over the network and is decoded back to the original list of strings.
"""
def encode(self, strs: List[str]) ->str:
"""
Encodes a list of strings to a single string.
Args:
strs: List of strings to encode
Returns:
str: Encoded string
"""
if len(strs) == 0:
return chr(258)
separator = chr(257)
return separator.join(strs)
def decode(self, s: str) ->List[str]:
"""
Decodes a single string to a list of strings.
Args:
s: Encoded string
Returns:
List[str]: Decoded list of strings
"""
if s == chr(258):
return []
separator = chr(257)
return s.split(separator)
def encode_length_prefixed(self, strs: List[str]) ->str:
"""
Encodes a list of strings to a single string using length prefixing.
Format: [length]#[string][length]#[string]...
Args:
strs: List of strings to encode
Returns:
str: Encoded string
"""
result = ''
for s in strs:
result += str(len(s)) + '#' + s
return result
def decode_length_prefixed(self, s: str) ->List[str]:
"""
Decodes a single string to a list of strings using length prefixing.
Args:
s: Encoded string
Returns:
List[str]: Decoded list of strings
"""
result = []
i = 0
while i < len(s):
j = i
while s[j] != '#':
j += 1
length = int(s[i:j])
i = j + 1
result.append(s[i:i + length])
i += length
return result
if __name__ == '__main__':
# Example usage based on LeetCode sample
codec = Codec()
# Example 1
strs1 = ["Hello", "World"]
print(f"Example 1 Input: {strs1}")
# Using character separator approach
encoded1 = codec.encode(strs1)
print(f"Encoded: {encoded1!r}")
decoded1 = codec.decode(encoded1)
print(f"Decoded: {decoded1}")
print(f"Matching original: {strs1 == decoded1}")
# Using length-prefixed approach
encoded1_lp = codec.encode_length_prefixed(strs1)
print(f"\nLength-prefixed encoded: {encoded1_lp!r}")
decoded1_lp = codec.decode_length_prefixed(encoded1_lp)
print(f"Length-prefixed decoded: {decoded1_lp}")
print(f"Matching original: {strs1 == decoded1_lp}")
# Example 2
strs2 = [""]
print(f"\nExample 2 Input: {strs2}")
# Using character separator approach
encoded2 = codec.encode(strs2)
print(f"Encoded: {encoded2!r}")
decoded2 = codec.decode(encoded2)
print(f"Decoded: {decoded2}")
print(f"Matching original: {strs2 == decoded2}")
# Using length-prefixed approach
encoded2_lp = codec.encode_length_prefixed(strs2)
print(f"\nLength-prefixed encoded: {encoded2_lp!r}")
decoded2_lp = codec.decode_length_prefixed(encoded2_lp)
print(f"Length-prefixed decoded: {decoded2_lp}")
print(f"Matching original: {strs2 == decoded2_lp}")
# Example with special characters
strs3 = ["#", "a#b", "c##d", "", "###"]
print(f"\nSpecial characters Input: {strs3}")
# Using length-prefixed approach (more robust with special characters)
encoded3_lp = codec.encode_length_prefixed(strs3)
print(f"Length-prefixed encoded: {encoded3_lp!r}")
decoded3_lp = codec.decode_length_prefixed(encoded3_lp)
print(f"Length-prefixed decoded: {decoded3_lp}")
print(f"Matching original: {strs3 == decoded3_lp}")
</pre>
</div>
</div>
</div>
<script>
const inputStrings = ["Hello", "World", "#test", "12#ab"];
let encoded = '';
let decoded = [];
let phase = 'init'; // init, encoding, betweenPhases, decoding, done
let currentIndex = 0;
let autoInterval = null;
let decodePos = 0;
function init() {
renderInput();
document.getElementById('encodedContainer').innerHTML = '<span style="color: #999;">Will appear here...</span>';
renderDecoded([]);
document.getElementById('encodePhase').classList.remove('active');
document.getElementById('decodePhase').classList.remove('active');
}
function renderInput() {
const container = document.getElementById('inputContainer');
container.innerHTML = '';
inputStrings.forEach((str, idx) => {
const box = document.createElement('div');
box.className = 'array-box';
box.id = `input-${idx}`;
box.style.width = 'auto';
box.style.minWidth = '80px';
box.style.padding = '10px 15px';
box.innerHTML = `"${str}"<span class="index-label">[${idx}]</span>`;
container.appendChild(box);
});
}
function renderEncoded(highlight = -1, highlightEnd = -1) {
const container = document.getElementById('encodedContainer');
if (encoded === '') {
container.innerHTML = '<span style="color: #999;">Building...</span>';
return;
}
let html = '';
for (let i = 0; i < encoded.length; i++) {
let style = '';
if (i >= highlight && i < highlightEnd && highlight >= 0) {
style = 'background: #ffeb3b; padding: 2px;';
}
html += `<span style="${style}">${encoded[i] === '#' ? '<span style="color: #f44336; font-weight: bold;">#</span>' : encoded[i]}</span>`;
}
container.innerHTML = `"${html}"`;
}
function renderDecoded(arr) {
const container = document.getElementById('decodedContainer');
container.innerHTML = '';
arr.forEach((str, idx) => {
const box = document.createElement('div');
box.className = 'array-box complete';
box.id = `decoded-${idx}`;
box.style.width = 'auto';
box.style.minWidth = '80px';
box.style.padding = '10px 15px';
box.innerHTML = `"${str}"<span class="index-label">[${idx}]</span>`;
container.appendChild(box);
});
}
function step() {
if (phase === 'init') {
phase = 'encoding';
currentIndex = 0;
encoded = '';
document.getElementById('encodePhase').classList.add('active');
document.getElementById('statusMessage').textContent = 'Starting to encode each string with length prefix...';
} else if (phase === 'encoding') {
if (currentIndex < inputStrings.length) {
const str = inputStrings[currentIndex];
const prefix = str.length + '#';
encoded += prefix + str;
// Highlight current input
document.querySelectorAll('.array-box').forEach(b => b.classList.remove('highlight'));
document.getElementById(`input-${currentIndex}`).classList.add('highlight');
renderEncoded();
document.getElementById('statusMessage').textContent =
`Encoding "${str}": Add "${prefix}" (length=${str.length}) + "${str}" → Total: "${encoded}"`;
currentIndex++;
} else {
phase = 'betweenPhases';
document.getElementById('encodePhase').classList.remove('active');
document.querySelectorAll('.array-box').forEach(b => b.classList.remove('highlight'));
document.getElementById('statusMessage').textContent =
`Encoding complete! Result: "${encoded}" — Now let's decode it back...`;
}
} else if (phase === 'betweenPhases') {
phase = 'decoding';
decodePos = 0;
decoded = [];
document.getElementById('decodePhase').classList.add('active');
document.getElementById('statusMessage').textContent = 'Starting decode: Read length, then read that many characters...';
} else if (phase === 'decoding') {
if (decodePos < encoded.length) {
// Find the #
let j = decodePos;
while (encoded[j] !== '#') j++;
const length = parseInt(encoded.substring(decodePos, j));
const start = j + 1;
const str = encoded.substring(start, start + length);
decoded.push(str);
renderEncoded(decodePos, start + length);
renderDecoded(decoded);
document.getElementById('statusMessage').textContent =
`Read length=${length} at position ${decodePos}, then read "${str}" (${length} chars). Decoded: [${decoded.map(s => `"${s}"`).join(', ')}]`;
decodePos = start + length;
} else {
phase = 'done';
document.getElementById('decodePhase').classList.remove('active');
renderEncoded();
document.getElementById('statusMessage').textContent =
`✅ Done! Successfully decoded back to: [${decoded.map(s => `"${s}"`).join(', ')}]`;
document.getElementById('stepBtn').disabled = true;
stopAuto();
}
}
}
function toggleAuto() {
if (autoInterval) {
stopAuto();
} else {
document.getElementById('autoBtn').textContent = 'Pause';
autoInterval = setInterval(() => {
if (phase === 'done') {
stopAuto();
} else {
step();
}
}, 1500);
}
}
function stopAuto() {
if (autoInterval) {
clearInterval(autoInterval);
autoInterval = null;
}
document.getElementById('autoBtn').textContent = 'Auto Run';
}
function reset() {
stopAuto();
phase = 'init';
currentIndex = 0;
encoded = '';
decoded = [];
decodePos = 0;
document.getElementById('stepBtn').disabled = false;
document.getElementById('statusMessage').textContent =
'Click "Step" or "Auto Run" to visualize encode/decode process';
init();
}
init();
</script>
</body>
</html>