干得好。递归方法,对通配符位置没有限制,您可以选择替换字符("01"
例如二进制计数或"0123456789"
所有自然字符。)
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
String input = "base 3 : **"; // the input, with wildcard
String replacable = "*"; // wildcard char
String replacedBy = "0123"; // all the possibilities for wildcard replacement
ArrayList<String> output = genCombinations(input, replacable, replacedBy);
// just print the results
for(String s : output)
System.out.println(s);
}
private static ArrayList<String> genCombinations(String input,String replacable, String replacement) {
StringBuilder sb = new StringBuilder(input);
ArrayList<String> out = new ArrayList<>(); //may warn with jdk < 1.7
// find the first wildcard
int index = input.indexOf(replacable);
if(index==-1){
//no wildcard found
out.add(sb.toString());
return out;
}
for(int i = 0; i<replacement.length(); ++i){
char c = replacement.charAt(i);
sb.setCharAt(index, c);
// gen all combination with the first wildcard already replaced
out.addAll(genCombinations(sb.toString(),replacable, replacement));
}
return out;
}
}
输出:
base 3 : 00
base 3 : 01
base 3 : 02
base 3 : 03
base 3 : 10
base 3 : 11
base 3 : 12
base 3 : 13
base 3 : 20
base 3 : 21
base 3 : 22
base 3 : 23
base 3 : 30
base 3 : 31
base 3 : 32
base 3 : 33