【LeetCode】 91. Decode Ways 解码方法(Medium)(JAVA)

【LeetCode】 91. Decode Ways 解码方法(Medium)(JAVA)

题目地址: https://leetcode.com/problems/decode-ways/

题目描述:

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).

题目大意

一条包含字母 A-Z 的消息通过以下方式进行了编码:

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

给定一个只包含数字的非空字符串,请计算解码方法的总数。

解题方法

1、采用动态规划,找出 dp 函数
2、考虑特殊情况,02 这种情况,0 不可开头

class Solution {
    public int numDecodings(String s) {
        if (s.length() == 0 || s.charAt(0) == '0') return 0;
        int[] dp = new int[s.length() + 1];
        dp[0] = 1;
        dp[1] = 1;
        for (int i = 1; i < s.length(); i++) {
            if (s.charAt(i) != '0') dp[i + 1] += dp[i];
            if (s.charAt(i - 1) != '0') {
                int sum = (s.charAt(i - 1) - '0') * 10 + s.charAt(i) - '0';
                if (sum >= 0 && sum <= 26) dp[i + 1] += dp[i - 1];
            }
        }
        return dp[s.length()];
    }
}

执行用时 : 1 ms, 在所有 Java 提交中击败了 100.00% 的用户
内存消耗 : 38.1 MB, 在所有 Java 提交中击败了 5.66% 的用户

猜你喜欢

转载自blog.csdn.net/qq_16927853/article/details/105434267