Skip to content

Commit c1cb3e1

Browse files
committed
solve(w05): 271. Encode and Decode Strings
1 parent 02ea8e9 commit c1cb3e1

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# https://leetcode.com/problems/encode-and-decode-strings/
2+
3+
from typing import List
4+
5+
class Codec:
6+
def encode(self, strs: List[str]) -> str:
7+
"""Encodes a list of strings to a single string.
8+
9+
[Approach]
10+
(length + delimiter + string)의 형태로 str를 구성하면 length 만큼 포인터를 건너뛰며 확인할 수 있게 된다.
11+
delimiter는 숫자(length) 바로 뒤에 처음으로 나오는 문자여야 하므로, 숫자가 아닌 값으로 해야 한다. (나는 "."으로)
12+
"""
13+
# length + delimiter + string
14+
return f"".join(str(len(s)) + "." + s for s in strs)
15+
16+
def decode(self, s: str) -> List[str]:
17+
"""Decodes a single string to a list of strings.
18+
"""
19+
strs = []
20+
21+
start = 0
22+
while start < len(s):
23+
# 1. start 이후에 나오는 첫 delimiter 위치 찾기
24+
# for delim in range(start, len(s)):
25+
# if s[delim] == ".":
26+
# break
27+
delim = s.find(".", start)
28+
29+
# 2. 보고 있는 str의 length 구하기
30+
length = int(s[start:delim])
31+
32+
# 3. 보고 있는 str의 다음 위치 구하기
33+
end = delim + 1 + length
34+
35+
# 4. 현재 str 모으기
36+
strs.append(s[delim + 1:end])
37+
38+
# 5. start를 end로 이동
39+
start = end
40+
41+
return strs
42+
43+
# Your Codec object will be instantiated and called as such:
44+
# codec = Codec()
45+
# codec.decode(codec.encode(strs))

0 commit comments

Comments
 (0)