# 2 原题

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.

# 3 AC解

public class Solution {
//基本来说遇到0要特殊处理，0的dp和他之前两位的是一样的，并且要检查是否符合要求，
//其他情况么，就是如果不能喝前一个树构成1-26的数组，那么dp就等于之前的位置，反之为之前两个位置之和
public int numDecodings(String s) {
if(s.length()==0 || s.charAt(0)== '0') return 0;
int path[]=new int[s.length()];
for(int i=0;i<s.length();i++)
path[i] = s.charAt(i)-'0';
int dp[]=new int[s.length()+1];
dp[1]=1;
dp[0]=1;
for(int i=2;i<=path.length;i++){
if(path[i-1]==0){
if(path[i-2]*10+path[i-1]<10 || path[i-2]*10+path[i-1]>26 ) return 0;
dp[i]=dp[i-2];
continue;
}
dp[i]=dp[i-1];
if(path[i-2]>0 && path[i-2]*10+path[i-1]<27 && path[i-2]*10+path[i-1]>9 )
dp[i]+=dp[i-2];
}
return dp[path.length];

}
}


• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120