Decode Ways(Medium) 解码方式

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.

动态规划

state: dp[i]表示前i个字符的总共decode的可能性

  1. 如果第i个字符(substring[i-1,i] )可以被decode, dp[i] += dp[i-1]
  2. 如果i-1, i字符(substring[i-2,i-1])可以decode, dp[i] += dp[i-2]

inital: dp[0] = 1 因为当长度为2时候找第二种情况就等于dp[0], 此时应该为1而不是0;dp[0]表示空字符串,有一种解码方式。

dp[1]表示字符串长度为1的解码方式。

dp[1] = 0 或者1 之所以要定义dp[1]因为我们要判定i-2的情况 所以单独列出来

public int numDecodings(String s) {
    if (s == null || s.length() == 0) {
        return 0;
    }
    int[] dp = new int[s.length() + 1];
    dp[0] = 1;
    dp[1] = s.charAt(0) != '0' ? 1 : 0;

    for (int i = 2; i <= s.length(); i++) {
        //单个字符
        if (isValid(s.substring(i - 1, i))) {
            dp[i] += dp[i - 1];
        }

        //2个字符
        if (isValid(s.substring(i - 2, i))) {
            dp[i] += dp[i - 2];
        }
    }
    return dp[s.length()];
}

public boolean isValid(String s) {
    if (s == null || s.length() == 0) {
        return false;
    }
    if (s.charAt(0) == '0') {
        return false;
    }
    int tem = Integer.parseInt(s);//把string变为int
    return tem >= 1 && tem <= 26;
}

results matching ""

    No results matching ""