Skip to content

Commit 97b0607

Browse files
committed
encode-and-decode-strings solution (py)
1 parent 7387261 commit 97b0607

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# ๋ฌธ์ œ: https://neetcode.io/problems/string-encode-and-decode
2+
# TC: O(N), SC: O(1)
3+
# ASCII ๋ฌธ์ž์—ด์ด ์•„๋‹Œ ์ด๋ชจํ‹ฐ์ฝ˜์œผ๋กœ ๊ตฌ๋ถ„์ž ์„ ํƒ
4+
5+
class Solution:
6+
def encode(self, strs: List[str]) -> str:
7+
return '๐Ÿค'.join(strs)
8+
9+
def decode(self, s: str) -> List[str]:
10+
return s.split('๐Ÿค')
11+
12+
# ASCII ๋ฌธ์ž์—ด์— ํฌํ•จ๋œ ๊ธฐํ˜ธ๋กœ ๊ตฌ๋ถ„์ž๋ฅผ ์จ์•ผํ•  ๋•Œ
13+
# -> ๊ธ€์ž ์ˆ˜ ํ‘œ์‹œ
14+
class Solution:
15+
def encode(self, strs: List[str]) -> str:
16+
text = ""
17+
for str in strs:
18+
text += f"{len(str)}:{str}"
19+
return text
20+
21+
def decode(self, s: str) -> List[str]:
22+
ls, start = [], 0
23+
while start < len(s):
24+
mid = s.find(":", start)
25+
length = int(s[start : mid])
26+
word = s[mid + 1 : mid + 1 + length]
27+
ls.append(word)
28+
start = mid + 1 + length
29+
return ls
30+

0 commit comments

Comments
ย (0)