From 9f1b9a6f6e3a64211668de2b851d2e38d3f430d0 Mon Sep 17 00:00:00 2001 From: Lanre Adedara Date: Mon, 27 May 2024 09:20:06 +0100 Subject: [PATCH] Swift implementation for LCOF 46 --- .../README.md" | 32 +++++++++++++++++++ .../Solution.swift" | 27 ++++++++++++++++ 2 files changed, 59 insertions(+) create mode 100644 "lcof/\351\235\242\350\257\225\351\242\23046. \346\212\212\346\225\260\345\255\227\347\277\273\350\257\221\346\210\220\345\255\227\347\254\246\344\270\262/Solution.swift" diff --git "a/lcof/\351\235\242\350\257\225\351\242\23046. \346\212\212\346\225\260\345\255\227\347\277\273\350\257\221\346\210\220\345\255\227\347\254\246\344\270\262/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23046. \346\212\212\346\225\260\345\255\227\347\277\273\350\257\221\346\210\220\345\255\227\347\254\246\344\270\262/README.md" index bc4507327b5fb..98773024f9f8a 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23046. \346\212\212\346\225\260\345\255\227\347\277\273\350\257\221\346\210\220\345\255\227\347\254\246\344\270\262/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23046. \346\212\212\346\225\260\345\255\227\347\277\273\350\257\221\346\210\220\345\255\227\347\254\246\344\270\262/README.md" @@ -252,6 +252,38 @@ public class Solution { } ``` +#### Swift + +```swift +class Solution { + private var n: Int = 0 + private var s: [Character] = [] + private var memo: [Int?] = [] + + func translateNum(_ num: Int) -> Int { + s = Array(String(num)) + n = s.count + memo = [Int?](repeating: nil, count: n) + return dfs(0) + } + + private func dfs(_ i: Int) -> Int { + if i >= n - 1 { + return 1 + } + if let cachedResult = memo[i] { + return cachedResult + } + var ans = dfs(i + 1) + if s[i] == "1" || (s[i] == "2" && s[i + 1] < "6") { + ans += dfs(i + 2) + } + memo[i] = ans + return ans + } +} +``` + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23046. \346\212\212\346\225\260\345\255\227\347\277\273\350\257\221\346\210\220\345\255\227\347\254\246\344\270\262/Solution.swift" "b/lcof/\351\235\242\350\257\225\351\242\23046. \346\212\212\346\225\260\345\255\227\347\277\273\350\257\221\346\210\220\345\255\227\347\254\246\344\270\262/Solution.swift" new file mode 100644 index 0000000000000..f3d8f4ee7fe4e --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23046. \346\212\212\346\225\260\345\255\227\347\277\273\350\257\221\346\210\220\345\255\227\347\254\246\344\270\262/Solution.swift" @@ -0,0 +1,27 @@ +class Solution { + private var n: Int = 0 + private var s: [Character] = [] + private var memo: [Int?] = [] + + func translateNum(_ num: Int) -> Int { + s = Array(String(num)) + n = s.count + memo = [Int?](repeating: nil, count: n) + return dfs(0) + } + + private func dfs(_ i: Int) -> Int { + if i >= n - 1 { + return 1 + } + if let cachedResult = memo[i] { + return cachedResult + } + var ans = dfs(i + 1) + if s[i] == "1" || (s[i] == "2" && s[i + 1] < "6") { + ans += dfs(i + 2) + } + memo[i] = ans + return ans + } +} \ No newline at end of file