LeetCode每日一题:解码的方法数

问题描述

A message containing letters from A-Z is being encoded to numbers using the following mapping:
'A' -> 1
'B' -> 2
...
'Z' -> 26
Given an encoded message containing digits, determine the total number of ways to decode it.
For example,
Given encoded message"12", it could be decoded as"AB"(1 2) or"L"(12).
The number of ways decoding"12"is 2.

问题分析

这道题可以用动态规划来做,设dp[i]表示s前i个字符有多少种解码方法,那么只用考虑最后后面两个字符s.charAt(i-2)和s.charAt(i-1):

  • 若这两个字符的值在[10,26]之间,将两个字符放在一起解码,说明dp[i]=dp[i]+dp[i-2],
  • 若s.charAt(i-1)!=‘0’,说明还可以用dp[i-1]来进行解码,那么dp[i]=dp[i]+dp[i-1],

只需考虑上面两种情况即可

代码实现

public int numDecodings(String s) {
        if (s.length() == 0 || s.charAt(0) == '0') return 0;
        if (s.length() == 1 && s.charAt(0) != '0') return 1;
        int[] dp = new int[s.length() + 1];
        dp[0] = dp[1] = 1;
        for (int i = 2; i <= s.length(); i++) {
            int num = Integer.parseInt(s.substring(i - 2, i));
            if (10 <= num && num <= 26) dp[i] = dp[i] + dp[i - 2];
            if (s.charAt(i - 1) != '0') dp[i] = dp[i] + dp[i - 1];
        }
        return dp[s.length()];
    }

你可能感兴趣的:(LeetCode每日一题:解码的方法数)