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.
解题思路: 使用动态规划,遍历字符串将当前子串的解码方式记录在数组ways中,遍历到第i+1个字符记录到ways[i]中
解法一:超时
public class Solution {
public int count(String s,int index,int end,int num){
if(index>=end){
return num;
}
int code1=s.charAt(index)-48;
if(code1<=2&&code1>=1){
int code2=s.charAt(index+1)-48;
int data=code1*10+code2;
if(data<=26){
num++;
num=count(s,index+2,end,num);
}
}
num=count(s,index+1,end,num);
return num;
}
public int numDecodings(String s) {
int ways=0;
if(s==null||s.equals("")){
return ways;
}
ways=count(s,0,s.length()-1,1);
return ways;
}
}
解法二: 动态规划
public class Solution {
public int decoding(char a, char b){
if(b=='0'){
if(a<='2'&&a>='1'){
return 2;
}else{
return -1;
}
}else{
if(a=='1'||(a=='2'&&b<='6')){
return 1;
}
return 0;
}
}
public int numDecodings(String s) {
if(s==null||s.equals("")){
return 0;
}
int len=s.length();
int [] ways=new int[len];
if(s.charAt(0)!='0'){
ways[0]=1;
}else{
return 0;
}
for(int i=1;i<len;i++){
int code=decoding(s.charAt(i-1),s.charAt(i));
switch(code){
case -1:
return 0;
case 2 :
if(i==1){
ways[i]=ways[i-1];
}else{
ways[i]=ways[i-2];
}
break;
case 1:
if(i==1){
ways[i]=ways[i-1]+1;
}else{
ways[i]=ways[i-1]+ways[i-2];
}
break;
case 0:
ways[i]=ways[i-1];
break;
}
}
return ways[len-1];
}
}