亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

PHP獲取與給定字符串匹配的給定數組的可能字符串組合

PHP獲取與給定字符串匹配的給定數組的可能字符串組合

PHP
繁星coding 2022-01-24 09:21:06
我有一個包含一堆字符串的數組,我想找到所有可能的組合,無論它如何排序與給定的字符串/單詞匹配。$dictionary = ['flow', 'stack', 'stackover', 'over', 'code'];input: stackoverflowoutput:#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);
查看完整描述

1 回答

?
MYYA

TA貢獻1868條經驗 獲得超4個贊

對于這樣的問題,您想使用回溯


function splitString($string, $dict)

{

    $result = [];

    //if the string is already empty return empty array

    if (empty($string)) {

        return $result;

    }


    foreach ($dict as $idx => $term) {

        if (strpos($string, $term) === 0) {

            //if the term is at the start of string


            //get the rest of string

            $substr = substr($string, strlen($term));


            //if all of string has been processed return only current term

            if (empty($substr)) {

                return [[$term]];

            }

            //get the dictionary without used term

            $subDict = $dict;

            unset($subDict[$idx]);


            //get results of splitting the rest of string

            $sub = splitString($substr, $subDict);

            //merge them with current term

            if (!empty($sub)) {

                foreach ($sub as $subResult) {

                    $result[] = array_merge([$term], $subResult);

                }

            }

        }

    }


    return $result;

}


$input = "stackoverflow";

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


$output = splitString($input, $dict);


查看完整回答
反對 回復 2022-01-24
  • 1 回答
  • 0 關注
  • 150 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號