-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathencode_and_decode_strings.py
More file actions
56 lines (45 loc) · 1.36 KB
/
encode_and_decode_strings.py
File metadata and controls
56 lines (45 loc) · 1.36 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
46
47
48
49
50
51
52
53
54
55
56
"""
https://leetcode.com/problems/encode-and-decode-strings/description
Description
Design an algorithm to encode a list of strings to a string. The encoded string is then sent over the network and is decoded back to the original list of strings.
Please implement encode and decode
Wechat reply 【Google】 get the latest requent Interview questions. (wechat id : jiuzhang0607)
Example 1:
Input: ["lint","code","love","you"]
Output: ["lint","code","love","you"]
Explanation:
One possible encode method is: "lint:;code:;love:;you"
Example 2:
Input: ["we", "say", ":", "yes"]
Output: ["we", "say", ":", "yes"]
Explanation:
One possible encode method is: "we:;say:;:::;yes"
"""
from typing import List
DELIMITER = "π"
def encode(strs: List[str]) -> str:
result = ""
lengths = ""
concatted_strs = ""
for new_str in strs:
new_length = str(len(new_str))
lengths += new_length + ","
concatted_strs += new_str
result += lengths + DELIMITER + concatted_strs
return result
def decode(s: str) -> List[str]:
result = []
sizes = []
i = 0
while s[i] != DELIMITER:
current_size = ""
while s[i] != ",":
current_size += s[i]
i += 1
sizes.append(int(current_size))
i += 1
i += 1
for size in sizes:
result.append(s[i : i + size])
i += size
return result