File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed
encode-and-decode-strings Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change 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))
You canโt perform that action at this time.
0 commit comments