File tree Expand file tree Collapse file tree
encode-and-decode-strings Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ # 7๊ธฐ ํ์ด
2+ # ์๊ฐ ๋ณต์ก๋: O(n)
3+ # - ์ธ์ฝ๋ฉ ๋์ฝ๋ฉ ๋ชจ๋ ๋ฌธ์์ด ๋ฆฌ์คํธ์ ๊ธธ์ด์ ๋ฐ๋ผ ์๊ฐ ๋ณต์ก๋๊ฐ ๊ฒฐ์ ๋จ
4+ # ๊ณต๊ฐ ๋ณต์ก๋: O(1)
5+ # - ์ ๋ต ๋ณ์์ธ res๋ฅผ ์ ์ธํ๊ณ ๋ ๋ณ์๋ง ์ฐ์
6+
7+
8+ DELIMITER = "^"
9+
10+
11+ class Solution :
12+ def encode (self , strs ):
13+ # DELIMITER๋ฅผ ์ฌ์ด์ ๋๊ณ ๋จ์ด์ ๊ธ์ ์์ ๋จ์ด๋ฅผ concatํด์ ์ ์ฅํ๋ค.
14+ # ์) ["cat", "is", "cute"] -> "3^cat2^is4^cute"
15+ # ์ด๋ ๊ฒ ํด์ผ ๊ธ์ ์๋ฅผ ์์ธกํ๊ณ splitํ๊ธฐ ์ฌ์์ง๋ค.
16+ return "" .join (map (lambda x : f"{ len (x )} { DELIMITER } { x } " , strs ))
17+
18+ def decode (self , s ):
19+ res = []
20+ i = 0
21+ while i < len (s ):
22+ # i๋ฒ์งธ ๊ธ์๋ก๋ถํฐ ์ฒซ๋ฒ์งธ DELIMITER๊ฐ ๋์ค๋ ์ธ๋ฑ์ค๋ฅผ j๋ผ๊ณ ์นญํจ
23+ j = s .index (DELIMITER , i )
24+ word_len = int (s [i :j ]) # DELIMITER ์์ ๊ธ์๋ '๊ธ์ ์'์ด๋ฏ๋ก int๋ก ๋ณํ
25+ word = s [j + 1 :j + word_len + 1 ] # i๋ฒ์งธ๋ถํฐ ๊ธ์ ์ ๋งํผ ์๋ผ์ word๋ฅผ ์ฐพ์
26+ res .append (word )
27+ i = j + word_len + 1 # ์๋ฅธ ์ดํ์ index๋ฅผ ์๋ก์ด i๋ก ์ค์ ํ์ฌ ๋ค์ ๊ธ์ ์ฐพ์
28+ return res
You canโt perform that action at this time.
0 commit comments