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.
import java.util.*;
public class Solution {
public boolean iscode(String s){
if(s.charAt(0)=='0') return false;
for(int i=0;i<s.length()-1;i++){
char a=s.charAt(i);
char b=s.charAt(i+1);
if((a=='0'&&b=='0')||(a>='3'&&a<='9'&&b=='0')) return false;
}
return true;
}
public int numDecodings(String s) {
int len=s.length();
int[] code=new int[len];
if(len==0) return 0;
if(!iscode(s)) return 0;
if(len==1) return 1;
code[0]=0;
for(int i=1;i<s.length();i++){
char a=s.charAt(i-1),b=s.charAt(i);
if(b=='0') code[i]=2;
else if((a=='1'&&b>'0'&&b<='9')||(a=='2'&&b>'0'&&b<='6')) code[i]=1;
else code[i]=0;
}
int[] decode=new int[len];
for(int i=0;i<s.length();i++)
decode[i]=-1;
return numDecode(code,decode,len-1);
}
public int numDecode(int[] code,int[] decode,int i){
int len=i+1;
if(i<0) return 0;
if(decode[i]!=-1) return decode[i];
if(len==0){
decode[i]=0;
return 0;
}
if(len==1){
decode[i]=1;
return 1;
}
if(len==2&&code[len-1]==1){
decode[i]=2;
return 2;
}
else if(len==2&&code[len-1]==0){
decode[i]=1;
return 1;
}else if(len==2&&code[len-1]==2){
decode[i]=1;
return 1;
}
if(code[len-1]==1){
return decode[i]=numDecode(code,decode,i-2)+numDecode(code,decode,i-1);
}else if(code[len-1]==0) return decode[i]=numDecode(code,decode,i-1);
else return decode[i]=numDecode(code,decode,i-2);
}
}