Skip to content

[river20s] WEEK 03 solutions #1300

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Apr 20, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions decode-ways/river20s.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
class Solution(object):
def numDecodings(self, s):
"""
실제로 어떤 문자열로 바뀌는지는 중요하지 않음.
유효한 디코딩 경로가 몇 가지인가를 구하는 문제.
DP를 사용하여 각 자리수에 대해 가능한 경우의 수를 누적하여 계산.
DP[i]는 i번째 자리까지의 경우의 수를 의미.
점화식: DP[i] = DP[i-1] + DP[i-2] (i >= 2)
Time complexity: O(n)
Space complexity: O(n)
"""
# 문자열이 비어있거나 '0'으로 시작하면 디코딩 X
if not s or s[0] == '0':
return 0

n = len(s)
dp = [0] * (n + 1)
dp[0] = 1 # DP를 위한 기초 상태 초기화, 실제로 빈 문자열이 들어오는 것은 아님
dp[1] = 1 # 첫 글자 디코딩 방법은 1가지

for i in range(2, n + 1):
# 한 자리 수 해석 가능 여부 확인
# s[i-2:i]는 i >= 2일때만 의미가 있으므로 2부터 루프 시작
if s[i - 1] != '0': # '0'은 유효하지 않으므로 제외
dp[i] += dp[i - 1] # 유효한 '1'~'9'라면 앞까지의 경우의 수를 계승

# 두 자리 수 해석 가능 여부 확인
if 10 <= int(s[i -2:i]) <= 26:
dp[i] += dp[i - 2] # 유효한 '10'~'26'이라면 앞까지의 경우의 수를 계승

return dp[n]
13 changes: 13 additions & 0 deletions number-of-1-bits/river20s.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
Time complexity: O(1)
Space complexity: O(1)
"""
count = 0
for _ in range(32):
count += n & 1
n >>= 1
return count
7 changes: 7 additions & 0 deletions valid-palindrome/river20s.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import re

class Solution(object):
def isPalindrome(self, s):
s = s.lower()
s = re.sub(r'[^a-z0-9]', '', s)
return s == s[::-1]