Skip to content

Commit a995ccc

Browse files
authored
feat: add swift implementation to lcof problem: No.46 (doocs#2927)
1 parent 4da24b1 commit a995ccc

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

lcof/面试题46. 把数字翻译成字符串/README.md

+32
Original file line numberDiff line numberDiff line change
@@ -252,6 +252,38 @@ public class Solution {
252252
}
253253
```
254254

255+
#### Swift
256+
257+
```swift
258+
class Solution {
259+
private var n: Int = 0
260+
private var s: [Character] = []
261+
private var memo: [Int?] = []
262+
263+
func translateNum(_ num: Int) -> Int {
264+
s = Array(String(num))
265+
n = s.count
266+
memo = [Int?](repeating: nil, count: n)
267+
return dfs(0)
268+
}
269+
270+
private func dfs(_ i: Int) -> Int {
271+
if i >= n - 1 {
272+
return 1
273+
}
274+
if let cachedResult = memo[i] {
275+
return cachedResult
276+
}
277+
var ans = dfs(i + 1)
278+
if s[i] == "1" || (s[i] == "2" && s[i + 1] < "6") {
279+
ans += dfs(i + 2)
280+
}
281+
memo[i] = ans
282+
return ans
283+
}
284+
}
285+
```
286+
255287
<!-- tabs:end -->
256288

257289
<!-- solution:end -->
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
class Solution {
2+
private var n: Int = 0
3+
private var s: [Character] = []
4+
private var memo: [Int?] = []
5+
6+
func translateNum(_ num: Int) -> Int {
7+
s = Array(String(num))
8+
n = s.count
9+
memo = [Int?](repeating: nil, count: n)
10+
return dfs(0)
11+
}
12+
13+
private func dfs(_ i: Int) -> Int {
14+
if i >= n - 1 {
15+
return 1
16+
}
17+
if let cachedResult = memo[i] {
18+
return cachedResult
19+
}
20+
var ans = dfs(i + 1)
21+
if s[i] == "1" || (s[i] == "2" && s[i + 1] < "6") {
22+
ans += dfs(i + 2)
23+
}
24+
memo[i] = ans
25+
return ans
26+
}
27+
}

0 commit comments

Comments
 (0)