我有这段代码,它为我提供了大小为 4 的数组 {'a', 'b', 'c', 'd'} 的四个元素的所有可能组合。
一切正常,但我需要在代码中添加一些规范,但我不知道如何去做。
我必须添加的两个条件是: 在字符串中,“b”后面必须始终跟有“a”,并且一个字符串不能同时包含字符“d”和字符“a”。
static void printAllKLength(char[] set, int k) {
int n = set.length;
printAllKLengthRec(set, "", n, k);
}
static void printAllKLengthRec (char[] set,
String prefix,
int n, int k)
{
if (k == 0) {
System.out.println(prefix);
return;
}
for (int i = 0; i < n; ++i) {
String newPrefix = prefix + set[i];
printAllKLengthRec(set, newPrefix,
n, k - 1);
}
}
public static void main(String[] args) {
char[] set1 = {'a', 'b', 'c', 'd'};
int k = 4;
printAllKLength(set1, k);
}
}
编辑 因此,感谢一些帮助,我编写了这段代码:
public static boolean aFollowsB(String s) {
char[] set1 = s.toCharArray();
for (int i = 0; i < set1.length; i++) {
// If B is the last char, A can't possilby follow
if (i == set1.length - 1) {
if (set1[i] == 'b') { return false; }
// Else if we encounter B, make sure next is an A
} else {
if (set1[i] == 'b') {
if (set1[i+1] != 'a') { return false; }
}
}
}
return true;
}
//Création de la méthode permettant de dire qu'on ne peut avoir 'a' et 'd' dans la même string
public static boolean hasOnlyAOrD(String s) {
char[] set1 = s.toCharArray();
boolean hasA = false;
boolean hasD = false;
for (int i = 0; i < set1.length; i++) {
if (set1[i] == 'a') {
hasA = true;
} else if (set1[i] == 'd') {
hasD = true;
}
}
if (hasA && hasD) {
return false;
}
return true;
}
//Création de la méthode printAllKLength pour imprimer toutes les strings possibles de longueur k
static void printAllKLength(char[] set, int k) {
int n = set.length;
printAllKLengthRec(set, "", n, k);
}
static void printAllKLengthRec (char[] set,
String prefix,
int n, int k)
{
if (k == 0) {
System.out.println(prefix);
System.out.println(prefix);
return;
}
for (int i = 0; i < n; ++i) {
String newPrefix = prefix + set[i];
printAllKLengthRec(set, newPrefix,
n, k - 1);
}
}
public static void main(String[] args) {
char[] set1 = {'a', 'b', 'c', 'd'};
int k = 4;
if (aFollowsB(set1) && hasOnlyAOrD(prefix)) {
printAllKLength(set1, k);
}
}}
但它说方法 aFollowsB 和 hasOnlyAorD 不适用于参数...
最佳答案
创建以下两个方法 - 或类似的方法(逻辑在这里)。
public static boolean aFollowsB(String s) {
char[] set = s.toCharArray();
for (int i = 0; i < set.length; i++) {
// If B is the last char, A can't possilby follow
if (i == set.length - 1) {
if (set[i] == 'b') { return false; }
// Else if we encounter B, make sure next is an A
} else {
if (set[i] == 'b') {
if (set[i+1] != 'a') { return false; }
}
}
}
return true;
}
public static boolean hasOnlyAOrD(String s) {
char[] set = s.toCharArray();
boolean hasA = false;
boolean hasD = false;
for (int i = 0; i < set.length; i++) {
if (set[i] == 'a') {
hasA = true;
} else if (set[i] == 'd') {
hasD = true;
}
}
if (hasA && hasD) {
return false;
}
return true;
}
现在,像这样包围你的打印语句:
if (aFollowsB(prefix) && hasOnlyAOrD(prefix)) {
System.out.println(prefix);
}
关于java - 给定大小为 n 的数组中 r 个元素在条件下的所有可能组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59293543/