Skip to content

Commit 1a4ae3a

Browse files
committed
Create 0091-decode-ways.swift
1 parent 0c0a712 commit 1a4ae3a

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

swift/0091-decode-ways.swift

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
class Solution {
2+
func numDecodings(_ s: String) -> Int {
3+
var s = Array(s)
4+
var dp: [Int: Int] = [s.count: 1]
5+
for i in stride(from: s.count - 1, to: -1, by: -1) {
6+
if s[i] == "0" {
7+
dp[i] = 0
8+
} else {
9+
dp[i] = dp[i + 1]
10+
}
11+
12+
if i + 1 < s.count && (s[i] == "1" || s[i] == "2" && "0123456".contains(s[i + 1])) {
13+
dp[i, default: 0] += dp[i + 2] ?? 0
14+
}
15+
}
16+
return dp[0]!
17+
}
18+
}

0 commit comments

Comments
 (0)