获取所有可能的子串在PHP
问题描述:
我试图让输入的所有字符串列表。 输入= A,子串{ '', '一个'} 输入= AB,子串{ '', 'A', 'B', 'AB', 'BA'} 输入= ABC,子串{ '', 'A', 'b', 'C', 'AB', 'BC', 'CA', 'BA', 'CB', 'AC', 'ABC', 'ACB', 'BAC' 'BCA', '出租车', 'CBA'} 等。获取所有可能的子串在PHP
我尝试的代码是在这里
function get_substr($string){
$array=str_split($string);
static $k=0;
for ($i=0; $i <count($array) ; $i++) {
for ($j=0; $j <count($array) ; $j++) {
$new_array[$k]=substr($string, $i, $j - $i + 1);
$k++;
}
}
return($new_array);
}
和我有这个代码的O/P如下
请建议我什么样的变化,我需要或任何其他想法来做这项工作。
答
<?php
// function to generate and print all N! permutations of $str. (N = strlen($str)).
function permute($str,$i = null,$n = null) {
if(is_null($n)) $n = mb_strlen($str);
if(is_null($i)) $i = 0;
if ($i == $n)
print "$str \n";
else {
for ($j = $i; $j < $n; $j++) {
swap($str,$i,$j);
permute($str, $i+1, $n);
swap($str,$i,$j); // backtrack.
}
}
}
// function to swap the char at pos $i and $j of $str.
function swap(&$str,$i,$j) {
$temp = $str[$i];
$str[$i] = $str[$j];
$str[$j] = $temp;
}
$str = "hey";
permute($str); // call the function.
看到这个SO answer
置换是解决 –
您需要的输出是*不*子。 'ba'不是'abc'的子字符串。 – Eiko
对不起@Eiko。如果您对我的问题有任何想法,请。 –