LeetCode 91 Decode Ways (dp)

A message containing letters from A-Z is being encoded to numbers using the following mapping:

'A' -> 1
'B' -> 2
...
'Z' -> 26

Given a non-empty string containing only digits, determine the total number of ways to decode it.

Example 1:

Input: "12"
Output: 2
Explanation: It could be decoded as "AB" (1 2) or "L" (12).

Example 2:

Input: "226"
Output: 3
Explanation: It could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6).

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

题目分析:设dp[i]为到位置i时的decode方案数,本题的0是一个坑点,包含0的只能是10或20

1ms,时间击败88.96%,容易发现第i个位置的状态只和i-1,i-2有关,因此可以用三个变量进行转移

class Solution {
    public int numDecodings(String s) {
        int n = s.length();
        int[] dp = new int[n + 1];
        dp[0] = s.charAt(0) == '0' ? 0 : 1;
        dp[1] = dp[0];
        for (int i = 2; i <= n; i++) {
            dp[i] = s.charAt(i - 1) == '0' ? 0 : dp[i - 1];
            if (s.charAt(i - 2) == '1' ||
                (s.charAt(i - 2) == '2' &&s.charAt(i - 1) <= '6')) {
                dp[i] += dp[i - 2];
            }
        }
        return dp[n];
    }
}

 

上一篇:力扣91.解码方法


下一篇:Python练习题 017:三支乒乓球队出赛名单