猿问

PHP获取与给定字符串匹配的给定数组的可能字符串组合

我有一个包含一堆字符串的数组,我想找到所有可能的组合,无论它如何排序与给定的字符串/单词匹配。


$dictionary = ['flow', 'stack', 'stackover', 'over', 'code'];


input: stackoverflow

output:

#1 -> ['stack', 'over', 'flow']

#2 -> ['stackover', 'flow']

我尝试过的是,我需要排除不包含在输入字符串中的数组元素,然后尝试将每个合并的元素与它匹配,但我不确定并被卡住了。谁能帮我想办法解决这个问题?提前谢谢你,这是我到目前为止的代码


<?php


$dict = ['flow', 'stack', 'stackover', 'over', 'code'];

$word = 'stackoverflow';


$dictHas = [];

foreach ($dict as $w) {

    if (strpos($word, $w) !== false) {

      $dictHas[] = $w;

    }

}


$result = [];

foreach ($dictHas as $el) {

    foreach ($dictHas as $wo) {

        $merge = $el . $wo;

        if ($merge == $word) {


        } elseif ((strpos($word, $merge) !== false) {


        }

    }

}


print_r($result);


繁星coding
浏览 130回答 1
1回答

MYYA

对于这样的问题,您想使用回溯function splitString($string, $dict){&nbsp; &nbsp; $result = [];&nbsp; &nbsp; //if the string is already empty return empty array&nbsp; &nbsp; if (empty($string)) {&nbsp; &nbsp; &nbsp; &nbsp; return $result;&nbsp; &nbsp; }&nbsp; &nbsp; foreach ($dict as $idx => $term) {&nbsp; &nbsp; &nbsp; &nbsp; if (strpos($string, $term) === 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //if the term is at the start of string&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //get the rest of string&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $substr = substr($string, strlen($term));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //if all of string has been processed return only current term&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (empty($substr)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return [[$term]];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //get the dictionary without used term&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $subDict = $dict;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; unset($subDict[$idx]);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //get results of splitting the rest of string&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $sub = splitString($substr, $subDict);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //merge them with current term&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (!empty($sub)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; foreach ($sub as $subResult) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $result[] = array_merge([$term], $subResult);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return $result;}$input = "stackoverflow";$dict = ['flow', 'stack', 'stackover', 'over', 'code'];$output = splitString($input, $dict);
随时随地看视频慕课网APP
我要回答