-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstring_encode_decode.py
More file actions
38 lines (31 loc) · 1.06 KB
/
string_encode_decode.py
File metadata and controls
38 lines (31 loc) · 1.06 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
# Design an algorithm to encode a list of strings to a single string. The encoded string is then decoded back to the original list of strings.
class Solution:
def encode(self, strs: List[str]) -> str:
res = ''
for s in strs:
res += str(len(s)) + '#' + s
return res
# "4#leet4#code"
# O(n)
def decode(self, s: str) -> List[str]:
res = []
i = 0
# iterate through string
while i < len(s):
# set second index to start of word pre delimeter
j = i
# loop through until reaching the delimeter
while s[j] != '#':
j += 1
# length = encoded int length of word parsed back to int
length = int(s[i:j])
# set i to start of word
i = j + 1
# set j to end of word
j = i + length
# append word to result array
res.append(s[i:j])
# set i to start at end of parsed word
i = j
return res
# O(n)