Skip to content

Commit 1110625

Browse files
Merge pull request #1487 from printjin-gmailcom/main
[printjin-gmailcom] Week 8 solutions
2 parents 738554e + 15a60ed commit 1110625

File tree

5 files changed

+65
-0
lines changed

5 files changed

+65
-0
lines changed

clone-graph/printjin-gmailcom.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
from collections import deque
2+
from typing import Optional
3+
4+
class Solution:
5+
def cloneGraph(self, node: Optional['Node']) -> Optional['Node']:
6+
if not node:
7+
return None
8+
old_to_new = {node: Node(node.val)}
9+
queue = deque([node])
10+
while queue:
11+
current = queue.popleft()
12+
for neighbor in current.neighbors:
13+
if neighbor not in old_to_new:
14+
old_to_new[neighbor] = Node(neighbor.val)
15+
queue.append(neighbor)
16+
old_to_new[current].neighbors.append(old_to_new[neighbor])
17+
return old_to_new[node]
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
class Solution:
2+
def longestCommonSubsequence(self, text1, text2):
3+
m, n = len(text1), len(text2)
4+
dp = [[0] * (n + 1) for _ in range(m + 1)]
5+
for i in range(1, m + 1):
6+
for j in range(1, n + 1):
7+
if text1[i - 1] == text2[j - 1]:
8+
dp[i][j] = dp[i - 1][j - 1] + 1
9+
else:
10+
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
11+
return dp[m][n]
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
class Solution:
2+
def characterReplacement(self, s, k):
3+
count = [0] * 26
4+
left = 0
5+
max_count = 0
6+
res = 0
7+
for right in range(len(s)):
8+
count[ord(s[right]) - ord('A')] += 1
9+
max_count = max(max_count, count[ord(s[right]) - ord('A')])
10+
while (right - left + 1) - max_count > k:
11+
count[ord(s[left]) - ord('A')] -= 1
12+
left += 1
13+
res = max(res, right - left + 1)
14+
return res
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
class Solution:
2+
def countSubstrings(self, s):
3+
count = 0
4+
for center in range(len(s)):
5+
left, right = center, center
6+
while left >= 0 and right < len(s) and s[left] == s[right]:
7+
count += 1
8+
left -= 1
9+
right += 1
10+
left, right = center, center + 1
11+
while left >= 0 and right < len(s) and s[left] == s[right]:
12+
count += 1
13+
left -= 1
14+
right += 1
15+
return count

reverse-bits/printjin-gmailcom.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
class Solution:
2+
def reverseBits(self, n):
3+
n = (n >> 16) | (n << 16)
4+
n = ((n & 0xff00ff00) >> 8) | ((n & 0x00ff00ff) << 8)
5+
n = ((n & 0xf0f0f0f0) >> 4) | ((n & 0x0f0f0f0f) << 4)
6+
n = ((n & 0xcccccccc) >> 2) | ((n & 0x33333333) << 2)
7+
n = ((n & 0xaaaaaaaa) >> 1) | ((n & 0x55555555) << 1)
8+
return n

0 commit comments

Comments
 (0)