繁体   English   中英

找到正确的算法来找到所有可能的二进制组合

[英]find the correct algorithme to find all the possible binary combination

我正在尝试编写一个名为showStar的非递归 Java 方法,它接受一个字符串,并生成该字符串的所有可能组合,而没有掩码“*”字符。

receiving this as an input "1011*00*10", 
the method `showStar` will display output like:
1011000010
1011000110
1011100010
1011100110

我尝试过这种方式,但是,一旦可能的案例数量超过字符串长度,输出就不准确。

这是我的代码。

public static void showStar(String s){
        String save;
        int count = 0;
        int poss;

        save = s.replace('*','0');
        StringBuilder myString = new StringBuilder(save);

        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '*' && myString.charAt(i) == '0') {
                myString.setCharAt(i, '1');
                System.out.println(myString);
            }
        }
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '*' && myString.charAt(i) == '1') {
                myString.setCharAt(i, '0');
                System.out.println(myString);
            }
        }

        }

假设有 k *s。 然后有 2^k 个解决方案。 您可以通过按顺序复制整数 0 - 2^k-1 中的位来生成这些。 (添加足够的前导零)

例如 1**1:

0 = 00 => 1001
1 = 01 => 1011
2 = 10 => 1101
3 = 11 => 1111

这里递归算法完美地工作:

  1. 您可以使用x = str.indexOf('*');检查输入字符串是否包含星号 '*' x = str.indexOf('*');
  2. 如果不存在星号(x == -1) ,则只需打印字符串并返回
  3. 否则,您将位置处的星号替换为“0”和“1”,并为这两个替换递归调用showStar()
public static void showStar(String str) {
    int x = str.indexOf('*');
    if(x == -1) {
        System.out.println(str);
        return;
    }
    String prefix = str.substring(0, x);
    String suffix = str.substring(x + 1);
    for (char i = '0'; i <= '1'; i++) {
        showStar(prefix + i + suffix);
    }
}

更新
在非递归实现中,我们需要收集星号位置,然后准备二进制表示并在已知位置设置适当的位:

public static void showStar(String str) {
    int[] xs = IntStream.range(0, str.length())
                        .filter(i -> str.charAt(i) == '*')
                        .toArray();
    int num = (int) Math.pow(2, xs.length); // 2^n variants for n asterisks
    String format = xs.length > 0 ? "%" + xs.length + "s" : "%s"; // fix if no '*'

    for (int i = 0; i < num; i++) {
        String bin = String.format(format, Integer.toBinaryString(i))
                           .replace(' ', '0');  // pad leading zeros
        StringBuilder sb = new StringBuilder(str);

        // set 0 or 1 in place of asterisk(s)
        for (int j = 0; j < xs.length; j++) {
            sb.setCharAt(xs[j], bin.charAt(j));
        }
            
        System.out.println(sb);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM