我试图找到一串数字的所有可能的解码的字符串的所有decodings,例如递归方法如下寻找数字
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);
}
}
请帮我看看什么是错的我的实施。我吮吸递归,所以我正在试图证明我的技能。谢谢
请告诉我们这行是第20 – ajb 2014-11-04 18:09:29
我建议像'的System.out.println (n)'就在导致问题的'charAt'行之前。它可能会帮助您查看您的逻辑中可能存在哪些错误。或者使用调试器。 – ajb 2014-11-04 18:12:59