动态规划——数字字符串转换为字母组合的种数(decode-ways)

本文介绍了一种解码数字字符串的算法,该算法基于给定的A-Z字母映射到1-26数字的规则,计算出解码的可能方式总数。通过动态规划的方法实现了高效求解,并详细阐述了实现过程中的注意事项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述

A message containing letters fromA-Zis 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.

例如,当我们知道了n-2长度的字符串能够解释的数目以及n-1长度的字符串能够解释的数目时,我们可以判读如下两个条件:

1)若第n个字符在1到9之间,则n长度的字符串能够解释的数目包含n-1长度字符串能够解释的数目。
2)若第n-1个字符与第n个字符可以解释为一个字母时,则n长度的字符串能够解释的数目包含n-2长度字符串能够解释的数目。

需要注意的地方:

s.charAt(0)不能为0,否则return 0;


public class Solution {
    public int numDecodings(String s) {
        if(s == null||s.length() == 0||s.charAt(0) == '0')
            return 0;
        if(s.length() == 1)
            {
            if(s.charAt(0)!='0')
                return 1;
            else
                return 0;
        }
        //dp[i]存放charAt(0)到charAt(i)所能代表的字母组合的个数
        int[] dp=new int[s.length()];
        dp[0]=1;
        dp[1]=(s.charAt(1)!='0'?1:0)+((char2int(s.charAt(0))*10+char2int(s.charAt(1)))<=26?1:0);
        for(int i=2;i<s.length();i++)
            {
            if(s.charAt(i)!='0')//
                dp[i]+=dp[i-1];
            if(s.charAt(i-1)!='0'&&(char2int(s.charAt(i-1))*10+char2int(s.charAt(i))<=26))
                dp[i]+=dp[i-2];
        }
        return dp[s.length()-1];
    }
    public int char2int(char c)
        {
        return c-'0';
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值