forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathseungriyou.py
More file actions
45 lines (34 loc) ยท 1.49 KB
/
seungriyou.py
File metadata and controls
45 lines (34 loc) ยท 1.49 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
# https://leetcode.com/problems/encode-and-decode-strings/
from typing import List
class Codec:
def encode(self, strs: List[str]) -> str:
"""Encodes a list of strings to a single string.
[Approach]
(length + delimiter + string)์ ํํ๋ก str๋ฅผ ๊ตฌ์ฑํ๋ฉด length ๋งํผ ํฌ์ธํฐ๋ฅผ ๊ฑด๋๋ฐ๋ฉฐ ํ์ธํ ์ ์๊ฒ ๋๋ค.
delimiter๋ ์ซ์(length) ๋ฐ๋ก ๋ค์ ์ฒ์์ผ๋ก ๋์ค๋ ๋ฌธ์์ฌ์ผ ํ๋ฏ๋ก, ์ซ์๊ฐ ์๋ ๊ฐ์ผ๋ก ํด์ผ ํ๋ค. (๋๋ "."์ผ๋ก)
"""
# length + delimiter + string
return f"".join(str(len(s)) + "." + s for s in strs)
def decode(self, s: str) -> List[str]:
"""Decodes a single string to a list of strings.
"""
strs = []
start = 0
while start < len(s):
# 1. start ์ดํ์ ๋์ค๋ ์ฒซ delimiter ์์น ์ฐพ๊ธฐ
# for delim in range(start, len(s)):
# if s[delim] == ".":
# break
delim = s.find(".", start)
# 2. ๋ณด๊ณ ์๋ str์ length ๊ตฌํ๊ธฐ
length = int(s[start:delim])
# 3. ๋ณด๊ณ ์๋ str์ ๋ค์ ์์น ๊ตฌํ๊ธฐ
end = delim + 1 + length
# 4. ํ์ฌ str ๋ชจ์ผ๊ธฐ
strs.append(s[delim + 1:end])
# 5. start๋ฅผ end๋ก ์ด๋
start = end
return strs
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.decode(codec.encode(strs))