这是我的问题代码
假设a的值= 1,b = 2,c = 3,...,z =26。为您提供了一个数字字符串S。
编写一个程序以返回可以从其中生成的所有可能代码的列表。给定的字符串。
import java.util.*;
public class solution {
// Return a string array that contains all possible codes
public static String[] getCode(String input){
// Write your code here
List<String> arrStr = new ArrayList<>();
printAllPossibleCodes(input, "", arrStr);
// for(String name: arrStr) {
// System.out.println(name);
// }
String[] arr = new String[arrStr.size()];
for(int j =0; j < arrStr.size(); j++){
arr[j] = arrStr.get(j);
}
return arr;
}
public static char getChar(int n){
return (char) (n+96);
}
public static void printAllPossibleCodes(String input, String ans, List<String> arrStr){
if(input.length() == 0){
//System.out.println(ans);
arrStr.add(ans);
return;
}
int firstDigit = input.charAt(0) - '0';
printAllPossibleCodes(input.substring(1), ans + getChar(firstDigit), arrStr);
if(input.length() > 1){
int firstTwoDigits = (input.charAt(0) - '0') * 10 + (input.charAt(1) - '0');
if(firstTwoDigits >= 10 && firstTwoDigits <= 20){
printAllPossibleCodes(input.substring(2), ans + getChar(firstTwoDigits), arrStr);
}
}
}
}
通过“ 35411”的测试时,输入“ 123”和“ 1123”的测试用例失败。
我的代码哪里出问题了?
您需要10 <= firstTwoDigits <= 20
在printAllPossibleCodes
两位数的情况下递归调用。但是,由于英文字母中有26个字母,因此要求为10 <= firstTwoDigits <= 26
。您的前两个测试用例失败,因为它们包含"23"
作为子字符串,该子字符串不在10到20之间。但是,第三个测试用例不包含大于20但小于27的两位数字子字符串,因此不会出现此问题。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句