Skip to content

Commit 7426ef7

Browse files
committed
[7th batch] week 5 - encode and decode strings
1 parent 478d56d commit 7426ef7

1 file changed

Lines changed: 28 additions & 0 deletions

File tree

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
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

0 commit comments

Comments
ย (0)