i am trying to find all possible decoding of a string of numbers, for example the following
Input: {1, 2, 1}
Output: ("aba", "au", "la")
[3 interpretations: aba(1,2,1), au(1,21), la(12,1)]
My program pints "aba" then gives me the following error
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 3
at java.lang.String.charAt(String.java:686)
at countDecoding.decodings(countDecoding.java:20)
at countDecoding.decodings(countDecoding.java:17)
at countDecoding.decodings(countDecoding.java:17)
at countDecoding.main(countDecoding.java:37)
line 20 is if((str.charAt(n)<'2' && str.charAt(n+1)!='0') || (str.charAt(n)=='2' && str.charAt(n+1)<'6')){
and line 17 is decodings(str,n=n+1,temp,len);
below is my code
public class countDecoding {
static void decodings(String str, int n,String temp,int len){
if(n == len ){
System.out.println(temp);
return;
}
if(str.charAt(n)>='0'){
char[] c = Character.toChars(96 + str.charAt(n)-'0');
temp = temp +c[0];
decodings(str,n=n+1,temp,len);
}
if((str.charAt(n)<'2' && str.charAt(n+1)!='0') || (str.charAt(n)=='2' && str.charAt(n+1)<'6')){
String hold = "";
hold+=str.charAt(n);
hold+=str.charAt(n+1);
char[] c = Character.toChars(96 + (Integer.parseInt(hold)));
temp = temp +c[0];
System.out.println("temp is "+temp);
decodings(str,n=n+2,temp,len);
}
}
public static void main(String[]args){
String str="121";
decodings(str, 0,"",3);
}
}
Please help me find what is wrong with my implementation. I suck at recursion, so i am trying to horn my skills. Thanks