Skip to content

Commit 40601be

Browse files
committed
Add decode ways solution
1 parent 0f731bc commit 40601be

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

decode-ways/hyunjung-choi.kt

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
class Solution {
2+
fun numDecodings(s: String): Int {
3+
if (s.isEmpty() || s[0] == '0') return 0
4+
5+
val n = s.length
6+
val dp = IntArray(n + 1)
7+
8+
dp[0] = 1
9+
dp[1] = 1
10+
11+
for (i in 2..n) {
12+
val currentChar = s[i - 1]
13+
val prevChar = s[i - 2]
14+
15+
if (currentChar != '0') {
16+
dp[i] += dp[i - 1]
17+
}
18+
19+
val twoDigit = (prevChar - '0') * 10 + (currentChar - '0')
20+
if (twoDigit in 10..26) {
21+
dp[i] += dp[i - 2]
22+
}
23+
}
24+
25+
return dp[n]
26+
}
27+
}

0 commit comments

Comments
 (0)