java - recursive method for finding all decodings of a string of numbers -
I am trying to find all possible decoding of a string of numbers, for example
Input: {1, 2, 1} Output: ("ABA", "AU", "LA") [3 Explanations: ABA (1,2,1), o (1,21), LA (12 , 1)]
My program pins "ABA" then gives me the following error
Exceptions in thread "main" java.lang.StringIndexOutOfBoundsException: string Index Count Out: java.lang.String.charAt (String.java:686) at 3 countDecoding.decodings (countDecoding.java: 20) at countDecoding.decodings (countDecoding.java:17) at countDecoding.decodings (countDecoding.java: 17) at countDecoding.main (countDecoding.java37) if line 20 is ((str.charAt (n) & lt; 2 '& Amp; str.charAt (n + 1)! =' 0 ') | | (Str.charAt (n) ==' 2 '& amp; str.charAt (n + 1) & lt; '6')) {and line 17 decodings (str, n = n + 1, temp, len);
Below is my code
public class count (static string, int n, string temporary, int lane) {if (n = lane) {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, floating, lane); } If (str.charAt (n) & lt; 2 '& amp; amp; amp; amp; str.charAt (n + 1)! =' 0 ') || (str.charAt (n) = = '2' & Str.charAt (n + 1) & lt; '6')) {string hold = ""; Hold = str.charAt (n); Hold = = str.charAt (n + 1); Four [] c = character. Tache (96 + (integer PRIIN (hold)); Temp = temp + c [0]; System.out.println ("is temporary" + floating); Decodings (str, n = n + 2, floating, lane); }} Public static zero main (string [] args) {string str = "121"; Decoding (str, 0, "", 3); }}
Please help to know what is wrong in my implementation I suck on repetition, so I am trying to horn my skills. Thanks
The problem goes from 0 ... n-1. Say length is 3 but should be str.charAt (n) n ... 2. You are calling it 3 with reference to the Fix it line:
if (str.charAt (n) & lt; 2 '& amp; amp; str.charAt ( N + 1)! = '0') || (Str.charAt (n) == '2' & amp; amp; str.charAt (n + 1)
<6 Errors are available because you are also doing N + 1 in the same priority.
Edit: Now check the code:
Private zero decode (string str, int n, string temporary, intel lane) {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, floating, lane); } System.out.println ("is temporary" + floating); } Public static zero main (string [] args) {string str = "121"; New Calculation Decoding () Decoding (str, 0, "", 3); }
Output is:
Abava temporal temporary temporary temporary
Comments
Post a Comment