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.
思路: 用f[i]表示,解密第0个至第i个字符的方法总数。
- 如果第i个字符不为0,那么第i个字符肯定是可以解析为一个字母,此时f[i]=f[i-1];
- 如果第i-1个字符不为0,如果第i-1个字符和第i个字符合起来可以解密为一个字母,此时f[i]应该等于第1步的结果再加上f[i-2];
- 否则,不满足前两步的条件,则f[i]=0;
public class Solution {
public int numDecodings(String s) {
int n=s.length();
if(n==0) return 0;
int[] f=new int[n];
if(s.charAt(0)=='0') return 0;
else f[0]=1;
if(n==1) return 1;
if(1<=Integer.parseInt(s.substring(0,2)) && Integer.parseInt(s.substring(0,2))<=26)
{
if(s.charAt(1)=='0') f[1]=1;
else f[1]=2;
}
else if(s.charAt(1)=='0') return 0;
else f[1]=1;
for(int i=2;i<n;i++)
{
f[i]=0;
if(s.charAt(i)!='0')
{
f[i]+=f[i-1];
}
if(s.charAt(i-1)!='0' && Integer.parseInt(s.substring(i-1,i+1)) <= 26)
f[i]+=f[i-2];
}
return f[n-1];
}
}