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

被折叠的 条评论
为什么被折叠?



