0

我有一个带空格的字符串。我需要拆分(分解)它并从中获取所有序列变体。例如:

字符串1 字符串2 字符串3

我需要解析它并得到这样的输出:

字符串1 字符串2 字符串3
字符串 1 字符串 3 字符串 2
字符串 2 字符串 1 字符串 3
字符串 2 字符串 3 字符串 1
字符串 3 字符串 2 字符串 1
字符串 3 字符串 1 字符串 2

最有效的方法是什么?
编辑:实际上我需要解析最多 3 个字符串。所以我这样做不是一个漂亮的方式(硬编码):

$exploded_query = explode(' ', $query);
如果(计数($exploded_query)== 2){
//2个变种
}
如果(计数($exploded_query)== 3){
//6 个变种
}

所以我正在寻找一些漂亮的方法来做到这一点。

4

2 回答 2

1

它是数组的排列

看这里 ->查找数组的所有排列,这对你有帮助。

于 2013-04-09T13:36:14.163 回答
0

我绝不是声称这是有效的或最佳的。那里有更好的解决方案。但这只是对您问题的直接回答。如果您想消除一些膨胀(以可能会降低一点性能为代价),您可以将getRemainingWords函数调用替换为:

$index = 0;
array_values(array_filter($words, function($key, &$index) { return !($key == $index++); }));

否则,这里是

function getPossibleCombinations($words) {
    $combinations = array();
    $count = count($words);

    // Base case: if there's only 1 word, there's only one combination
    if ($count == 1) {
        return array($words);
    }

    // Otherwise, loop over each words
    foreach ($words as $key=>$word) {

        // For each item, get all of the remaining items in the array (all except the current one)
        $otherWords = getRemainingWords($words, $key);

        // And recursively permute them
        $otherCombinations = getPossibleCombinations($otherWords);
        foreach ($otherCombinations as $otherCombination) {
            $combinations[] = array_merge(array($word), $otherCombination);
        }
    }

    return $combinations;
}


function getRemainingWords($array, $index) {
    $results = array();

    foreach ($array as $key=>$value) {
        if ($key == $index) {
            continue;
        }

        $results[] = $value;
    }

    return $results;
}
于 2013-04-09T13:08:46.743 回答