-
Notifications
You must be signed in to change notification settings - Fork 126
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
56 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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] ๋ฐํ: ์ต์ข ๋์ฝ๋ ๊ฐ๋ฅํ ๊ฒฝ์ฐ์ ์ ๊ฒฐ๊ณผ | ||
''' |