Skip to content

Commit

Permalink
add solution: decode-ways
Browse files Browse the repository at this point in the history
  • Loading branch information
dusunax committed Dec 21, 2024
1 parent c7d7f84 commit b506385
Showing 1 changed file with 56 additions and 0 deletions.
56 changes: 56 additions & 0 deletions decode-ways/dusunax.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
'''
# Leetcode 91. Decode Ways
use **dynamic programming** to solve this problem.
## Time and Space Complexity
```
TC: O(n)
SC: O(n)
```
### TC is O(n):
- iterating through the string and checking if the current character is decodable. = O(n)
### SC is O(n):
- creating a dp array of size n + 1 = O(n)
'''
class Solution:
def isDecodable(self, str: str):
return 1 <= int(str) <= 26 and str[0] != '0'

def numDecodings(self, s: str) -> int:
if s[0] == "0":
return 0

n = len(s)
dp = (n + 1) * [0]
dp[0] = 1
dp[1] = 1

for i in range(2, n + 1):
one = s[i - 1]
two = s[i - 2:i]

if self.isDecodable(one):
dp[i] += dp[i - 1]
if self.isDecodable(two):
dp[i] += dp[i - 2]

return dp[n]

'''
# sudo code
- ํ—ฌํผํ•จ์ˆ˜: 0์œผ๋กœ ์‹œ์ž‘ํ•˜์ง€ ์•Š๊ณ , 1~26์ธ ๊ฒฝ์šฐ True
- numDecodingsํ•จ์ˆ˜
1. n: ๋ฌธ์ž์—ด s์˜ ๊ธธ์ด
2. dp: ๊ฒฐ๊ณผ๋ฅผ ์ €์žฅํ•  ๋ฐฐ์—ด, n+1
3. BaseCase: dp[0] = 1, dp[1] = 1
4. for loop 2 to n:
one = s์˜ i-1 ์œ„์น˜์˜ 1๊ธ€์ž (ํ˜„์žฌ ๊ธ€์ž)
two = s์˜ i-2๋ถ€ํ„ฐ i๊นŒ์ง€ ์ž๋ฅธ 2๊ธ€์ž (ํ˜„์žฌ ๊ธ€์ž ํฌํ•จ ์ด์ „ ๊ธ€์ž)
if one is decodable => dp[i] += dp[i - 1] i๊ธธ์ด์ผ ๋•Œ, dp์˜ -1 ๊ฒฝ์šฐ์˜ ๋งŒํผ์ˆ˜ ์ถ”๊ฐ€ (ํ˜„์žฌ ๊ธ€์ž๋ฅผ ํ•œ ๊ธ€์ž๋กœ ํ•ด์„)
if two is decodable => dp[i] += dp[i - 2] i๊ธธ์ด์ผ ๋•Œ, dp์˜ -2 ๊ฒฝ์šฐ์˜ ์ˆ˜ ๋งŒํผ ์ถ”๊ฐ€ (ํ˜„์žฌ ๊ธ€์ž๋ฅผ ๋‘ ๊ธ€์ž๋กœ ํ•ด์„)
5. dp[n] ๋ฐ˜ํ™˜: ์ตœ์ข… ๋””์ฝ”๋“œ ๊ฐ€๋Šฅํ•œ ๊ฒฝ์šฐ์˜ ์ˆ˜ ๊ฒฐ๊ณผ
'''

0 comments on commit b506385

Please sign in to comment.