0

数字の文字列の可能なすべてのデコードを見つけようとしています。たとえば、次のようになります

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);

}

}

私の実装の問題点を見つけるのを手伝ってください。私は再帰が苦手なので、スキルを磨こうとしています。ありがとう

4

1 に答える 1

0

問題は、文字列が 0... n-1 になることです。長さは 3 ですが、str.charAt(n) n は 0 ~ 2 である必要があります。3 fix it で呼び出しています。参照する場合の行は次のとおりです。

if(str.charAt(n)<'2' && str.charAt(n+1)!='0')  || (str.charAt(n)=='2' && str.charAt(n+1)<'6'))

エラーが発生することを修正した後でも、同じ行で n+1 を実行しているためです。


編集:今すぐコードを確認してください:

private 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+1,temp,len);
    }
    System.out.println("temp is "+temp);
}

public static void main(String[]args){
    String str="121";
    new countDecoding().decodings(str, 0,"",3);
}

出力は:

aba
temp is aba
temp is ab
temp is a
于 2014-11-04T18:14:18.750 に答える