forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlylaminju.py
More file actions
71 lines (58 loc) ยท 2.29 KB
/
lylaminju.py
File metadata and controls
71 lines (58 loc) ยท 2.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# encode ๋ฉ์๋:
# ์๊ฐ ๋ณต์ก๋: O(N)
# - ๊ฐ ๋ฌธ์์ด์ ํ ๋ฒ์ฉ ์ํํ๋ฉฐ ๊ธธ์ด์ ๋ด์ฉ์ ์ฒ๋ฆฌํ๋ฏ๋ก, ๋ชจ๋ ๋ฌธ์์ด ๊ธธ์ด์ ํฉ์ ๋น๋ก.
# ๊ณต๊ฐ ๋ณต์ก๋: O(N)
# - ์ธ์ฝ๋ฉ๋ ๊ฒฐ๊ณผ ๋ฌธ์์ด์ ์ ์ฅํ๊ธฐ ์ํด ์ถ๊ฐ ๊ณต๊ฐ ์ฌ์ฉ.
# decode ๋ฉ์๋:
# ์๊ฐ ๋ณต์ก๋: O(N)
# - ์ธ์ฝ๋ฉ๋ ๋ฌธ์์ด์ ์ฒ์๋ถํฐ ๋๊น์ง ํ ๋ฒ ์ํํ๋ฉฐ ํ์ฑํ๋ฏ๋ก, ์
๋ ฅ ๋ฌธ์์ด ๊ธธ์ด์ ๋น๋ก.
# - s.find('#', i)๋ ์ธ๋ฑ์ค i๋ถํฐ ๋ค์ #๋ฅผ ์ฐพ์.
# - ์ฌ๋ฌ ๋ฒ์ find ํธ์ถ์ด ์๋๋ผ๋ ๊ฐ ํธ์ถ๋ง๋ค ์ ์ฒด ๋ฌธ์์ด์ ๋ค์ ํ์ํ์ง ์๊ณ ์ด์ ํ์ ์ดํ์ ๋ถ๋ถ๋ง ํ์ํ๊ฒ ๋์ด, ๋ชจ๋ find ํธ์ถ์ ํฉํ ์ ์ฒด ํ์ ๊ฑฐ๋ฆฌ๋ ์ธ์ฝ๋ฉ๋ ๋ฌธ์์ด์ ์ ์ฒด ๊ธธ์ด n์ ํด๋นํจ. ์ ์ฒด ์๊ฐ์ O(n)์ ์๋ ด.
# ๊ณต๊ฐ ๋ณต์ก๋: O(N)
# - ๋์ฝ๋ฉ๋ ๋ฌธ์์ด ๋ฆฌ์คํธ๋ฅผ ๊ตฌ์ฑํ๊ธฐ ์ํด ์ถ๊ฐ ๊ณต๊ฐ ์ฌ์ฉ.
class Solution:
"""
@param strs: a list of strings
@return: encodes a list of strings to a single string.
"""
def encode(self, strs):
encoded_str = ""
for s in strs:
encoded_str += (str(len(s)) + "#" + s)
return encoded_str
"""
@param s: A string
@return: decodes a single string to a list of strings
"""
def decode(self, s):
decoded_list = []
i = 0
while i < len(s):
j = s.find("#", i)
length = int(s[i:j])
i = j + 1
decoded_list.append(s[i:i + length])
i += length
return decoded_list
def main():
sol = Solution()
# ํ
์คํธ ์์ 1
input_strings1 = ["lint", "code", "love", "you"]
print("===== Example 1 =====")
print("Original: ", input_strings1)
encoded_str1 = sol.encode(input_strings1)
print("Encoded: ", encoded_str1)
decoded_list1 = sol.decode(encoded_str1)
print("Decoded: ", decoded_list1)
print()
# ํ
์คํธ ์์ 2
input_strings2 = ["1234567890a", "we", "say", "#", "yes"]
print("===== Example 2 =====")
print("Original: ", input_strings2)
encoded_str2 = sol.encode(input_strings2)
print("Encoded: ", encoded_str2)
decoded_list2 = sol.decode(encoded_str2)
print("Decoded: ", decoded_list2)
print()
if __name__ == "__main__":
main()