Skip to content
This repository was archived by the owner on Apr 27, 2025. It is now read-only.

Commit 8e6991f

Browse files
authored
Create 91. Decode Ways.md
1 parent abad375 commit 8e6991f

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

91. Decode Ways.md

+68
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
# 91. Decode Ways
2+
3+
### 2020-07-31
4+
5+
A message containing letters from A-Z is being encoded to numbers using the following mapping:
6+
7+
```
8+
'A' -> 1
9+
'B' -> 2
10+
...
11+
'Z' -> 26
12+
```
13+
Given a non-empty string containing only digits, determine the total number of ways to decode it.
14+
15+
Example 1:
16+
```
17+
Input: "12"
18+
Output: 2
19+
Explanation: It could be decoded as "AB" (1 2) or "L" (12).
20+
```
21+
Example 2:
22+
```
23+
Input: "226"
24+
Output: 3
25+
Explanation: It could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6).
26+
```
27+
28+
# Solution
29+
30+
```swift
31+
class Solution {
32+
private var cache = [Int]()
33+
private func numDecodingsForSubString(start: Int, end: Int, c: [Int8]) -> Int {
34+
let index = start * 2 + (end - start)
35+
if cache[index] >= 0 {
36+
return cache[index]
37+
}
38+
guard end <= c.count, c[start] != 0, isLetters(c[start..<end]) else {
39+
cache[index] = 0
40+
return 0
41+
}
42+
if end == c.count {
43+
cache[index] = 1
44+
return 1
45+
}
46+
let count = numDecodingsForSubString(start: end, end: end + 1, c: c) + numDecodingsForSubString(start: end, end: end + 2, c: c)
47+
cache[index] = count
48+
return count
49+
}
50+
51+
private func isLetters(_ array: ArraySlice<Int8>) -> Bool {
52+
var i = Int8(0)
53+
for c in array {
54+
i = i * 10 + c
55+
}
56+
return i >= 1 && i <= 26
57+
}
58+
59+
func numDecodings(_ s: String) -> Int {
60+
var c = s.utf8CString.map({ $0 - 48 })
61+
c.removeLast()
62+
cache = [Int].init(repeating: -1, count: c.count * 2 + 2)
63+
return numDecodingsForSubString(start: 0, end: 1, c: c) + numDecodingsForSubString(start: 0, end: 2, c: c)
64+
}
65+
}
66+
67+
68+
```

0 commit comments

Comments
 (0)