leetcode 第91题-解码方法

链接:https://leetcode-cn.com/problems/decode-ways

package leetcode

func NumDecodings(s string) int {
    if s[0] == '0' {
        return 0
    }

    dp := make([]int, len(s), len(s))
    dp[0] = 1
    //dp[i] = dp[i-1] + dp[i-2]
    for i := 1; i < len(s); i++ {
        if s[i] == '0' {
            if s[i-1] == '1' || s[i-1] == '2' {
                if i-2 < 0 {
                    dp[i] = 1
                } else {
                    dp[i] = dp[i-2]
                }
            } else {
                return 0
            }
            continue
        }

        if s[i-1] == '1' || (s[i-1] == '2' && s[i] <= '6') {
            if i-2 < 0 {
                dp[i] = dp[i-1] + 1
            } else {
                dp[i] = dp[i-1] + dp[i-2]
            }
            continue
        }

        dp[i] = dp[i-1]
    }

    return dp[len(s)-1]
}

你可能感兴趣的:(leetcode 第91题-解码方法)