Skip to content

Commit 277cc6f

Browse files
committed
solve: encode and decode strings
1 parent ec04268 commit 277cc6f

File tree

2 files changed

+56
-58
lines changed

2 files changed

+56
-58
lines changed

encode-and-decode-strings/sounmind.js

-58
This file was deleted.

encode-and-decode-strings/sounmind.py

+56
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
# Special character used as delimiter between length and actual string
6+
delimiter = "$"
7+
8+
def encode(self, strs: List[str]) -> str:
9+
"""
10+
Encodes a list of strings into a single string.
11+
Format: [length]$[string][length]$[string]...
12+
"""
13+
encoded = []
14+
# Encode each word using the format: length + delimiter + word
15+
for word in strs:
16+
# Convert word length to string, add delimiter, then add the word itself
17+
encoded.append(f"{len(word)}{self.delimiter}{word}")
18+
19+
# Join all encoded elements into a single string and return
20+
return "".join(encoded)
21+
22+
def decode(self, encoded: str) -> List[str]:
23+
"""
24+
Decodes a single string back to the original list of strings.
25+
"""
26+
decoded = [] # List to store the decoded strings
27+
current_index = 0 # Pointer to track current position in the encoded string
28+
29+
# Process the encoded string until we reach the end
30+
while current_index < len(encoded):
31+
# Starting from current_index, find the position of delimiter
32+
delimiter_index = current_index
33+
34+
# Move forward until we find the delimiter character
35+
while encoded[delimiter_index] != self.delimiter:
36+
delimiter_index += 1
37+
38+
# Extract and convert the length prefix to integer
39+
word_length = int(encoded[current_index:delimiter_index])
40+
41+
# Calculate the start position of the word (after the delimiter)
42+
word_start = delimiter_index + 1
43+
44+
# Calculate the end position of the word
45+
word_end = word_start + word_length
46+
47+
# Extract the word using the calculated positions
48+
word = encoded[word_start:word_end]
49+
50+
# Add the decoded word to our result list
51+
decoded.append(word)
52+
53+
# Move the current index to the end of this word for the next iteration
54+
current_index = word_end
55+
56+
return decoded

0 commit comments

Comments
 (0)