-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path271_encode_decode_string.py
More file actions
45 lines (37 loc) · 1.16 KB
/
271_encode_decode_string.py
File metadata and controls
45 lines (37 loc) · 1.16 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
from typing import List
class Solution:
def encode(self, strs: List[str]) -> str:
res = ""
for s in strs:
res += str(len(s)) + "#" + s
return res
def decode(self, s: str) -> List[str]:
res = []
i = 0
while i < len(s):
j = i
while s[j] != '#':
j += 1
length = int(s[i:j])
i = j + 1
j = i + length
res.append(s[i:j])
i = j
return res
def run_tests():
solution = Solution()
test_cases = [
[""], # Single empty string
[], # Empty list
["we", "say", ":", "yes"], # Multiple strings with special character
["neet", "code", "loves", "you"], # Multiple normal strings
["#hello#world", "with#delimiter#"], # Strings containing delimiter
]
for test in test_cases:
encoded = solution.encode(test)
decoded = solution.decode(encoded)
print(f"Original: {test}")
print(f"Encoded: {encoded}")
print(f"Decoded: {decoded}")
print(f"Pass: {test == decoded}\n")
run_tests()