Skip to content

Commit 47acb9b

Browse files
committed
encode and decode strings
1 parent d65d7b9 commit 47acb9b

1 file changed

Lines changed: 49 additions & 0 deletions

File tree

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
"""
6+
๊ฐ ๋ฌธ์ž์—ด์„ '๋ฌธ์ž์—ด ๊ธธ์ด#๋ฌธ์ž์—ด' ํ˜•์‹์œผ๋กœ ์ธ์ฝ”๋”ฉํ•œ๋‹ค.
7+
8+
์˜ˆ:
9+
["Hello", "World", ""]
10+
-> "5#Hello5#World0#"
11+
12+
์‹œ๊ฐ„ ๋ณต์žก๋„: O(n)
13+
๊ณต๊ฐ„ ๋ณต์žก๋„: O(n)
14+
15+
n์€ ๋ชจ๋“  ๋ฌธ์ž์—ด ๊ธธ์ด์˜ ํ•ฉ์ด๋‹ค.
16+
"""
17+
18+
def encode(self, strs: List[str]) -> str:
19+
encoded = []
20+
21+
for word in strs:
22+
encoded.append(f"{len(word)}#{word}")
23+
24+
return "".join(encoded)
25+
26+
def decode(self, encoded_string: str) -> List[str]:
27+
decoded = []
28+
index = 0
29+
30+
while index < len(encoded_string):
31+
delimiter_index = index
32+
33+
# ๋ฌธ์ž์—ด ๊ธธ์ด์™€ ์‹ค์ œ ๋ฌธ์ž์—ด์„ ๋‚˜๋ˆ„๋Š” '#'์„ ์ฐพ๋Š”๋‹ค.
34+
while encoded_string[delimiter_index] != "#":
35+
delimiter_index += 1
36+
37+
word_length = int(
38+
encoded_string[index:delimiter_index]
39+
)
40+
41+
word_start = delimiter_index + 1
42+
word_end = word_start + word_length
43+
44+
decoded.append(encoded_string[word_start:word_end])
45+
46+
# ๋‹ค์Œ ๋ฌธ์ž์—ด์˜ ๊ธธ์ด๊ฐ€ ์‹œ์ž‘๋˜๋Š” ์œ„์น˜๋กœ ์ด๋™ํ•œ๋‹ค.
47+
index = word_end
48+
49+
return decoded

0 commit comments

Comments
ย (0)