-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathencode_decode_strings.py
56 lines (39 loc) · 1.88 KB
/
encode_decode_strings.py
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
"""
Question: https://leetcode.com/problems/encode-and-decode-strings/ (Leetcode Premium)
OR
https://neetcode.io/problems/string-encode-and-decode (Free by Neetcode)
"""
class Solution:
def encode(self, input_str: str):
"""
Encode the individual strings as a single string by adding an integer and delimiter to the start of each string.
The integer indicates number of characters in the current string,
and the delimiter ('#') will separate the integer and the actual string.
Eg. ["lint","code","love","you"] will become "4#lint4#code4#love3#you" as the encoded string.
"""
encoded_str = ""
for s in input_str:
encoded_str += str(len(s)) + '#' + s
return encoded_str
def decode(self, encoded_str: str):
"""
We decode the encoded string as described in the `encode` method.
"""
decoded_str = []
# We use pointer `i` to keep track of where we are in the encoded str
i = 0
# Keep iterating until you go through the entire encoded string
while i < len(encoded_str):
# Introduce another pointer to find the delimiter we encoded
j = i
while encoded_str[j] != '#':
# We keep incrementing `j` until we find the delimiter
j += 1
# Here, we have encountered a delimiter. So we start decoding...
# Get the length of the current string
length = int(encoded_str[i:j])
# Splice the encoded string and append the extracted string to `decoded_strs`
decoded_str.append(encoded_str[j+1: j+1+length])
# Once you have the string extracted, update `i` to resume from the next string
i = j+1+length
return decoded_str