我有一个这样的字符串: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个单词连接在
根据我的理解,你需要所有可能的单词组合。所以:
- 可能的组合= amountofwords*amountofspaces。
- 开始迭代可能的组合。->
for(i=0;i<=(words*spaces);i++)
- 在
String
中包含数组中的单词和空格,因此$WordArray = $string.split(" ")
和$spaces = substr_count(" ")
- 开始迭代可能的单词组合。
for(j=0;j<=words;j++)
- 开始迭代空格量。
for(k=0;k<=spaces;++)
- 结合。
,但请记住,PERMUTATIONS and COMBINATIONS for computer science
是你首先需要学习的,所以上面的答案有很多道理。
这里有一个链接,让你开始。http://cpsc.ualr.edu/srini/DM/chapters/review3.4.html