Skip to content

Commit 2f50432

Browse files
committed
encode and decode strings solution
1 parent 4cddfb0 commit 2f50432

1 file changed

Lines changed: 58 additions & 0 deletions

File tree

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
class Solution:
2+
"""
3+
@param: strs: a list of strings
4+
@return: encodes a list of strings to a single string.
5+
"""
6+
def encode(self, strs):
7+
# write your code here
8+
# Encode each word with its length prefix and a "#"
9+
# ["C#", "&"] -> "2#C#1#&"
10+
encoded_str = ""
11+
12+
for word in strs:
13+
encoded_str += f"{len(word)}#{word}"
14+
15+
return encoded_str
16+
17+
"""
18+
@param: str: A string
19+
@return: decodes a single string to a list of strings
20+
"""
21+
def decode(self, str):
22+
# write your code here
23+
# "2#C#1#&" -> ["C#", "&"]
24+
decoded_lst = []
25+
char_count = 0
26+
reading_word = False
27+
word = ""
28+
length_str = ""
29+
30+
if str == "":
31+
return [""]
32+
33+
for ch in str:
34+
if ch == "#" and not reading_word:
35+
# Finished reading the length prefix
36+
# Switch to word-reading mode
37+
char_count = int(length_str)
38+
length_str = ""
39+
reading_word = True
40+
41+
elif not reading_word:
42+
# Accumulate digits for the length prefix
43+
length_str += ch
44+
45+
else:
46+
# reading_word is True
47+
word += ch
48+
char_count -= 1
49+
50+
if char_count == 0:
51+
reading_word = False
52+
decoded_lst.append(word)
53+
word = ""
54+
55+
return decoded_lst
56+
57+
# Time Complexity: O(N)
58+
# Space Complexity: O(N)

0 commit comments

Comments
 (0)