Skip to content

Commit d95596a

Browse files
committed
encode-and-decode-strings solution
1 parent 0310c80 commit d95596a

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
class Solution:
2+
"""
3+
@param: strs: a list of strings
4+
@return: encodes a list of strings to a single string.
5+
"""
6+
def encode(self, strs):
7+
# write your code here
8+
answer = ""
9+
10+
# ๋ฌธ์ž์—ด ์•ž์— "๋ฌธ์ž์—ด๊ธธ์ด + :" ๋ถ™์—ฌ์„œ ์ธ์ฝ”๋”ฉ
11+
for i in strs:
12+
answer += str(len(i)) + ":" + i
13+
14+
return answer
15+
16+
"""
17+
@param: str: A string
18+
@return: decodes a single string to a list of strings
19+
"""
20+
def decode(self, s): # ๋ณ€์ˆ˜๋ช…str์„ s๋กœ ์ˆ˜์ •
21+
# write your code here
22+
answer = []
23+
i = 0
24+
25+
# ":"๋ฅผ ๊ธฐ์ค€์œผ๋กœ ์•ž์— ์ˆซ์ž(๋ฌธ์ž์—ด๊ธธ์ด)๋งŒํผ ๋Š์–ด์„œ ๋””์ฝ”๋”ฉ
26+
while i < len(s):
27+
j = i
28+
29+
# ๋ฌธ์ž์—ด๊ธธ์ด๊ฐ€ ํ•œ์ž๋ฆฌ ์ด์ƒ์ผ ์ˆ˜ ์žˆ์œผ๋‹ˆ๊นŒ ":"๋ฅผ ๊ธฐ์ค€์œผ๋กœ ํ•จ
30+
while s[j] != ":":
31+
j += 1
32+
33+
length = int(s[i:j]) # ๋ฌธ์ž์—ด์˜ ๊ธธ์ด ์ถ”์ถœ
34+
answer.append(s[j+1:j+1+length]) # ๊ธธ์ด๋งŒํผ ๋ฌธ์ž์—ด ์ถ”์ถœํ•ด์„œ answer์— ๋„ฃ๊ธฐ
35+
i = j + 1 + length # ์ž˜๋ผ์ง„ ๋ฌธ์ž์—ด ๋’ค๋กœ ์ด๋™
36+
37+
return answer

0 commit comments

Comments
ย (0)