我试图找到一串数字的所有可能解码,例如以下
Input: {1, 2, 1}
Output: ("aba", "au", "la")
[3 interpretations: aba(1,2,1), au(1,21), la(12,1)]
我的程序品脱“aba”然后给我以下错误
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);
下面是我的代码
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);
}
}
请帮我找出我的实施有什么问题。我不擅长递归,所以我试图提高我的技能。谢谢