PHP字符串与所有的空间改变


php string with all space changing

我有一个这样的字符串:hello world new foo .

我需要这样的数组:

[
  `helloworld new foo`,
  `hello worldnew foo`,
  `hello world newfoo`,
  `helloworldnew foo`,
  `hello worldnewfoo`,
]

的顺序不重要,但我需要所有的情况下,空格将被删除在当前字符串

您可以使用递归枚举所有的可能性:

<?php
function combine($words, $acc=array(), $res=array()){
    if(count($words)===0){
        $res[] = join("", $acc);
        return $res;
    }
    if(count($words)===1){
        $res[] = join("", $acc).$words[0];
        return $res;
    }
    $w1 = array_shift($words);
    $res = combine($words,  array_merge($acc, array("$w1")),  $res);
    $res = combine($words,  array_merge($acc, array("$w1 ")), $res);
    return $res;
}
var_dump( combine( explode(' ', 'hello world new foo') ) );

另一个可能的解决方案是将单词之间的N个空格表示为二进制数字中的位,可以打开或关闭,然后从0到2^N-1计数,但我认为在PHP中这会更复杂。

注意:上面的递归解,返回所有可能的组合…因此,如果你有一个包含4个单词的输入数组,其中一个结果将是所有4个单词连接在

根据我的理解,你需要所有可能的单词组合。所以:

  1. 可能的组合= amountofwords*amountofspaces。
  2. 开始迭代可能的组合。-> for(i=0;i<=(words*spaces);i++)
  3. String中包含数组中的单词和空格,因此$WordArray = $string.split(" ")$spaces = substr_count(" ")
  4. 开始迭代可能的单词组合。for(j=0;j<=words;j++)
  5. 开始迭代空格量。for(k=0;k<=spaces;++)
  6. 结合。

,但请记住,PERMUTATIONS and COMBINATIONS for computer science是你首先需要学习的,所以上面的答案有很多道理。

这里有一个链接,让你开始。http://cpsc.ualr.edu/srini/DM/chapters/review3.4.html