File tree 1 file changed +31
-0
lines changed
1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution (object ):
2
+ def numDecodings (self , s ):
3
+ """
4
+ ์ค์ ๋ก ์ด๋ค ๋ฌธ์์ด๋ก ๋ฐ๋๋์ง๋ ์ค์ํ์ง ์์.
5
+ ์ ํจํ ๋์ฝ๋ฉ ๊ฒฝ๋ก๊ฐ ๋ช ๊ฐ์ง์ธ๊ฐ๋ฅผ ๊ตฌํ๋ ๋ฌธ์ .
6
+ DP๋ฅผ ์ฌ์ฉํ์ฌ ๊ฐ ์๋ฆฌ์์ ๋ํด ๊ฐ๋ฅํ ๊ฒฝ์ฐ์ ์๋ฅผ ๋์ ํ์ฌ ๊ณ์ฐ.
7
+ DP[i]๋ i๋ฒ์งธ ์๋ฆฌ๊น์ง์ ๊ฒฝ์ฐ์ ์๋ฅผ ์๋ฏธ.
8
+ ์ ํ์: DP[i] = DP[i-1] + DP[i-2] (i >= 2)
9
+ Time complexity: O(n)
10
+ Space complexity: O(n)
11
+ """
12
+ # ๋ฌธ์์ด์ด ๋น์ด์๊ฑฐ๋ '0'์ผ๋ก ์์ํ๋ฉด ๋์ฝ๋ฉ X
13
+ if not s or s [0 ] == '0' :
14
+ return 0
15
+
16
+ n = len (s )
17
+ dp = [0 ] * (n + 1 )
18
+ dp [0 ] = 1 # DP๋ฅผ ์ํ ๊ธฐ์ด ์ํ ์ด๊ธฐํ, ์ค์ ๋ก ๋น ๋ฌธ์์ด์ด ๋ค์ด์ค๋ ๊ฒ์ ์๋
19
+ dp [1 ] = 1 # ์ฒซ ๊ธ์ ๋์ฝ๋ฉ ๋ฐฉ๋ฒ์ 1๊ฐ์ง
20
+
21
+ for i in range (2 , n + 1 ):
22
+ # ํ ์๋ฆฌ ์ ํด์ ๊ฐ๋ฅ ์ฌ๋ถ ํ์ธ
23
+ # s[i-2:i]๋ i >= 2์ผ๋๋ง ์๋ฏธ๊ฐ ์์ผ๋ฏ๋ก 2๋ถํฐ ๋ฃจํ ์์
24
+ if s [i - 1 ] != '0' : # '0'์ ์ ํจํ์ง ์์ผ๋ฏ๋ก ์ ์ธ
25
+ dp [i ] += dp [i - 1 ] # ์ ํจํ '1'~'9'๋ผ๋ฉด ์๊น์ง์ ๊ฒฝ์ฐ์ ์๋ฅผ ๊ณ์น
26
+
27
+ # ๋ ์๋ฆฌ ์ ํด์ ๊ฐ๋ฅ ์ฌ๋ถ ํ์ธ
28
+ if 10 <= int (s [i - 2 :i ]) <= 26 :
29
+ dp [i ] += dp [i - 2 ] # ์ ํจํ '10'~'26'์ด๋ผ๋ฉด ์๊น์ง์ ๊ฒฝ์ฐ์ ์๋ฅผ ๊ณ์น
30
+
31
+ return dp [n ]
You canโt perform that action at this time.
0 commit comments