Skip to content

Commit 27f04bc

Browse files
author
changmuk.im
committed
solve : week 2 with python
1 parent 90e72e8 commit 27f04bc

File tree

5 files changed

+357
-0
lines changed

5 files changed

+357
-0
lines changed
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
from typing import List, Optional
2+
from unittest import TestCase, main
3+
4+
5+
# Definition for a binary tree node.
6+
class TreeNode:
7+
def __init__(self, val=0, left=None, right=None):
8+
self.val = val
9+
self.left = left
10+
self.right = right
11+
12+
13+
class Solution:
14+
def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
15+
return self.solve_1(preorder, inorder)
16+
17+
"""
18+
Runtime: 112 ms (Beats 66.16%)
19+
Time Complexity: O(n ** 2)
20+
Space Complexity: O(n)
21+
Memory: 52.83 MB (Beats 63.14%)
22+
"""
23+
def solve_1(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
24+
index = 0
25+
26+
def build_tree(preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
27+
nonlocal index
28+
29+
if not inorder:
30+
return None
31+
32+
if not 0 <= index < len(preorder):
33+
return None
34+
35+
root = TreeNode(preorder[index])
36+
index += 1
37+
split_index = inorder.index(root.val)
38+
root.left = build_tree(preorder, inorder[:split_index])
39+
root.right = build_tree(preorder, inorder[split_index + 1:])
40+
41+
return root
42+
43+
return build_tree(preorder, inorder)
44+
45+
46+
class _LeetCodeTestCases(TestCase):
47+
def test_1(self):
48+
preorder = [3, 9, 20, 15, 7]
49+
inorder = [9, 3, 15, 20, 7]
50+
output = TreeNode(
51+
val=3,
52+
left=TreeNode(
53+
val=9
54+
),
55+
right=TreeNode(
56+
val=20,
57+
left=TreeNode(val=15),
58+
right=TreeNode(val=7)
59+
)
60+
)
61+
self.assertEqual(Solution.buildTree(Solution(), preorder, inorder), output)
62+
63+
def test_2(self):
64+
preorder = [-1]
65+
inorder = [-1]
66+
output = TreeNode(
67+
val=-1
68+
)
69+
self.assertEqual(Solution.buildTree(Solution(), preorder, inorder), output)
70+
71+
def test_3(self):
72+
preorder = [1, 2]
73+
inorder = [1, 2]
74+
output = TreeNode(
75+
val=1,
76+
right=TreeNode(
77+
val=2
78+
)
79+
)
80+
self.assertEqual(Solution.buildTree(Solution(), preorder, inorder), output)
81+
82+
83+
if __name__ == '__main__':
84+
main()

counting-bits/EGON.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
from typing import List
2+
from unittest import TestCase, main
3+
4+
5+
class Solution:
6+
def countBits(self, n: int) -> List[int]:
7+
return self.solve_1(n)
8+
9+
"""
10+
Runtime: 78 ms (Beats 31.22%)
11+
Time Complexity: O(n * log n), 크기가 n인 배열의 원소들에 대해 시행마다 크기가 2로 나누어지는 비트연산을 수행하므로
12+
Space Complexity: O(1), 변수 저장 없이 바로 결과 반환
13+
Memory: 23.26 MB (Beats 39.52%)
14+
"""
15+
def solve_1(self, n: int) -> List[int]:
16+
def count_number_of_1(n: int):
17+
count = 0
18+
while n:
19+
n &= (n - 1)
20+
count += 1
21+
return count
22+
23+
return [count_number_of_1(num) for num in range(n + 1)]
24+
25+
26+
class _LeetCodeTestCases(TestCase):
27+
def test_1(self):
28+
n = 2
29+
output = [0, 1, 1]
30+
self.assertEqual(Solution.countBits(Solution(), n), output)
31+
32+
def test_2(self):
33+
n = 5
34+
output = [0, 1, 1, 2, 1, 2]
35+
self.assertEqual(Solution.countBits(Solution(), n), output)
36+
37+
38+
if __name__ == '__main__':
39+
main()

decode-ways/EGON.py

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
from typing import List
2+
from unittest import TestCase, main
3+
4+
5+
class Solution:
6+
def numDecodings(self, s: str) -> int:
7+
return self.solve_1(s)
8+
9+
"""
10+
Runtime: 32 ms (Beats 80.36%)
11+
Time Complexity: O(n)
12+
Space Complexity: O(n)
13+
Memory: 16.59 MB (Beats 51.72%)
14+
"""
15+
def solve_1(self, s: str) -> int:
16+
if len(s) == 0:
17+
return 0
18+
19+
if len(s) == 1:
20+
return 0 if int(s) == 0 else 1
21+
22+
if len(s) == 2:
23+
last_one_digit, last_two_digits = int(s[1]), int(s)
24+
if last_one_digit == 0:
25+
return 1 if 10 <= last_two_digits <= 26 else 0
26+
else:
27+
if 0 <= last_two_digits < 10:
28+
return 0
29+
elif 10 <= last_two_digits <= 26:
30+
return 2
31+
else:
32+
return 1
33+
34+
dp = [0] * (len(s) + 1)
35+
dp[0], dp[1], dp[2] = self.solve_1(s[:0]), self.solve_1(s[:1]), self.solve_1(s[:2])
36+
for i in range(3, len(s) + 1):
37+
last_one_digit, last_two_digits = int(s[i - 1]), int(s[i - 2: i])
38+
last_two_digits = int(s[i - 2: i])
39+
if last_one_digit == 0:
40+
dp[i] += dp[i - 2] if 10 <= last_two_digits <= 26 else 0
41+
else:
42+
dp[i] += dp[i - 1] + (dp[i - 2] if 10 <= last_two_digits <= 26 else 0)
43+
44+
return dp[-1]
45+
46+
47+
class _LeetCodeTestCases(TestCase):
48+
def test_1(self):
49+
s = "226"
50+
output = 3
51+
self.assertEqual(Solution.numDecodings(Solution(), s), output)
52+
53+
def test_2(self):
54+
s = "2101"
55+
output = 1
56+
self.assertEqual(Solution.numDecodings(Solution(), s), output)
57+
58+
def test_3(self):
59+
s = "06"
60+
output = 0
61+
self.assertEqual(Solution.numDecodings(Solution(), s), output)
62+
63+
64+
if __name__ == '__main__':
65+
main()

encode-and-decode-strings/EGON.py

Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
from functools import reduce
2+
from typing import List
3+
from unittest import TestCase, main
4+
5+
6+
class Solution:
7+
def encode(self, strs):
8+
return self.encode_with_base64(strs)
9+
10+
def decode(self, str):
11+
return self.decode_with_base64(str)
12+
13+
CSV_DELIMITER = ','
14+
15+
# solve_1. ASCII
16+
"""
17+
Runtime: -
18+
Time Complexity: O(n * m), n은 strs 배열의 길이, m은 strs 배열의 각 문자열들의 평균 길이
19+
Space Complexity: O(n * m), n은 strs 배열의 길이, m은 encode/decode된 문자열의 평균 길이
20+
Memory: -
21+
"""
22+
def encode_with_ascii(self, strs: List[str]) -> str:
23+
result = []
24+
for str in strs:
25+
encoded_str = reduce(
26+
lambda acc, cur: acc + cur,
27+
map(lambda char: f'{ord(char)}'.zfill(3), str)
28+
)
29+
result.append(encoded_str)
30+
31+
return Solution.CSV_DELIMITER.join(result)
32+
33+
def decode_with_ascii(self, str: str) -> List[str]:
34+
encoded_strs = str.split(Solution.CSV_DELIMITER)
35+
result = []
36+
for encoded_str in encoded_strs:
37+
decoded_str = ''
38+
for i in range(0, len(encoded_str), 3):
39+
chunk = encoded_str[i: i + 3]
40+
decoded_str += chr(int(chunk))
41+
result.append(decoded_str)
42+
43+
return result
44+
45+
# solve_2. Base64
46+
"""
47+
Runtime: -
48+
Time Complexity: O(n * m), n은 strs 배열의 길이, m은 strs 배열의 각 문자열들의 평균 길이
49+
Space Complexity: O(n * m), n은 strs 배열의 길이, m은 encode/decode된 문자열의 평균 길이
50+
Memory: -
51+
"""
52+
BASE64_CHAR_TABLE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
53+
54+
def encode_with_base64(self, strs: List[str]) -> str:
55+
result = []
56+
57+
for str in strs:
58+
bin_converted_str = reduce(
59+
lambda acc, cur: acc + cur,
60+
map(lambda char: bin(ord(char))[2:].zfill(8), str)
61+
)
62+
63+
encoded_str = ''
64+
for i in range(0, len(bin_converted_str), 6):
65+
chunk = bin_converted_str[i: i + 6].ljust(6, '0')
66+
base64_char = Solution.BASE64_CHAR_TABLE[int(chunk, 2)]
67+
encoded_str += base64_char
68+
encoded_str.ljust(4 - (len(encoded_str) % 4), '=')
69+
70+
result.append(encoded_str)
71+
72+
return Solution.CSV_DELIMITER.join(result)
73+
74+
def decode_with_base64(self, str: str) -> List[str]:
75+
result = []
76+
77+
encoded_strs = str.split(Solution.CSV_DELIMITER)
78+
for encoded_str in encoded_strs:
79+
encoded_str = encoded_str.rstrip('=')
80+
bin_converted_str = reduce(
81+
lambda acc, cur: acc + cur,
82+
map(lambda char: bin(Solution.BASE64_CHAR_TABLE.index(char))[2:].zfill(6), encoded_str)
83+
)
84+
85+
decoded_str = ''
86+
for i in range(0, len(bin_converted_str), 8):
87+
chunk = bin_converted_str[i: i + 8].rjust(8, '0')
88+
decimal_value = int(chunk, 2)
89+
if decimal_value != 0:
90+
decoded_str += chr(decimal_value)
91+
92+
result.append(decoded_str)
93+
94+
return result
95+
96+
97+
class _LeetCodeTestCases(TestCase):
98+
def test_1(self):
99+
input = ["lint", "code", "love", "you"]
100+
output = ["lint", "code", "love", "you"]
101+
solution = Solution()
102+
encoded = Solution.encode(solution, input)
103+
decoded = Solution.decode(solution, encoded)
104+
self.assertEqual(decoded, output)
105+
106+
def test_2(self):
107+
input = ["we", "say", ":", "yes"]
108+
output = ["we", "say", ":", "yes"]
109+
solution = Solution()
110+
encoded = Solution.encode(solution, input)
111+
decoded = Solution.decode(solution, encoded)
112+
self.assertEqual(decoded, output)
113+
114+
115+
if __name__ == '__main__':
116+
main()

valid-anagram/EGON.py

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
from unittest import TestCase, main
2+
from collections import Counter
3+
4+
5+
class Solution:
6+
def isAnagram(self, s: str, t: str) -> bool:
7+
return self.solve_1(s, t)
8+
9+
"""
10+
Runtime: 46 ms (Beats 71.98%)
11+
Time Complexity: O(n)
12+
- 길이가 n인 str s, str t, dict counter를 순회하므로 O(3n) ~= O(n)
13+
Space Complexity: O(n)
14+
- 크기가 최대 n인 dict를 변수로 저장하여 사용하므로 O(n)
15+
Memory: 16.88 MB (Beats 88.63%)
16+
"""
17+
def solve_1(self, s: str, t: str) -> bool:
18+
counter = {}
19+
for char in s:
20+
counter[char] = counter.get(char, 0) + 1
21+
for char in t:
22+
counter[char] = counter.get(char, 0) - 1
23+
24+
return any(counter.values()) is False
25+
26+
"""
27+
Runtime: 47 ms (Beats 67.45%)
28+
Time Complexity: O(n)
29+
- 크기가 n인 Counter 2개를 생성하므로 O(2n) ~= O(n)
30+
Space Complexity: O(n)
31+
- 크기가 n인 Counter 2개를 생성하므로 O(2n) ~= O(n)
32+
Memory: 16.94 MB (Beats 46.26%)
33+
"""
34+
def solve_2(self, s: str, t: str) -> bool:
35+
return Counter(s) is Counter(t)
36+
37+
38+
class _LeetCodeTestCases(TestCase):
39+
def test_1(self):
40+
s = "anagram"
41+
t = "nagaram"
42+
output = True
43+
self.assertEqual(Solution.isAnagram(Solution(), s, t), output)
44+
45+
def test_2(self):
46+
s = "rat"
47+
t = "car"
48+
output = True
49+
self.assertEqual(Solution.isAnagram(Solution(), s, t), output)
50+
51+
52+
if __name__ == '__main__':
53+
main()

0 commit comments

Comments
 (0)