【问题标题】:php string with all space changing [closed]所有空间都在变化的php字符串[关闭]
【发布时间】:2014-08-24 17:37:36
【问题描述】:

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

我需要这样的数组:

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

顺序无关紧要,但我需要在当前字符串中删除所有空格。

【问题讨论】:

  • 那么你有没有试过从这个字符串创建这个数组?

标签: php arrays string permutation


【解决方案1】:

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

<?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 中这将是更复杂。

NB:上述递归解决方案返回所有个可能的组合...所以如果您有一个包含 4 个单词的输入数组,其中一个结果将包含 所有 4 个单词 em>。

【讨论】:

    【解决方案2】:

    据我了解,您需要所有可能的组合与给定的单词。所以:

    1. 可能的组合 = 字数 * 空格数。
    2. 为可能的组合开始迭代。 -> for(i=0;i&lt;=(words*spaces);i++)
    3. String 中找到数组和空格中的单词,所以$WordArray = $string.split(" ")$spaces = substr_count(" ")
    4. 开始迭代可能的单词组合。 for(j=0;j&lt;=words;j++)
    5. 开始迭代空间数量。 for(k=0;k&lt;=spaces;++)
    6. 全部合并。

    但请记住,PERMUTATIONS and COMBINATIONS for computer science 是您首先需要学习的内容,因此上面的答案很有意义。

    这是一个帮助您入门的链接。 http://cpsc.ualr.edu/srini/DM/chapters/review3.4.html

    【讨论】:

      猜你喜欢
      • 2016-07-27
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-12
      • 1970-01-01
      • 2018-01-11
      • 2010-09-29
      相关资源
      最近更新 更多