[swift] Leetcode 91 S:39.77% M:50.00%

查看更多leetcode题目swift解法,前往https://jinblack.com/leetcode-swift/

https://leetcode.com/problems/decode-ways/

The problem is not so good for its wrong test case and bad problem design. Here i didn’t optimize my solution.

class Solution {
    func numDecodings(_ s: String) -> Int {
        let n = s.count
        guard n != 0 else { return 0 }
        var memo = Array<Int>(repeating: 0, count: n+1)
        memo[n] = 1
        memo[n-1] = s[s.index(before: s.endIndex)] != "0" ? 1 : 0
        if n-2 >= 0 {
            for i in Array(0...n-2).reversed() {
                let idx = s.index(s.startIndex, offsetBy: i)
                if s[idx] == "0" { continue }
                else {
                    memo[i] = (Int(s[idx...s.index(after: idx)])! <= 26) ? memo[i+1] + memo[i+2] : memo[i+1]
                }
            }
        }
        return memo[0]
    }
}

Runtime: 24 ms, faster than 39.77% of Swift online submissions for Decode Ways.
Memory Usage: 20.2 MB, less than 50.00% of Swift online submissions for Decode Ways.

猜你喜欢

转载自blog.csdn.net/weixin_44146252/article/details/88291280