如何在PHP中生成字符串的所有排列?我需要一個算法,它返回一個字符串中所有字符的所有可能組合。我試過了:$langd = strlen($input);
for($i = 0;$i < $langd; $i++){
$tempStrang = NULL;
$tempStrang .= substr($input, $i, 1);
for($j = $i+1, $k=0; $k < $langd; $k++, $j++){
if($j > $langd) $j = 0;
$tempStrang .= substr($input, $j, 1);
}
$myarray[] = $tempStrang;}但是,它只返回與字符串長度相同的數量組合。說$input = "hey",結果將是:hey, hye, eyh, ehy, yhe, yeh。
3 回答

梵蒂岡之花
TA貢獻1900條經驗 獲得超5個贊
您可以使用基于反向跟蹤的方法系統地生成所有排列:
// function to generate and print all N! permutations of $str. (N = strlen($str)).function permute($str,$i,$n) { 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,0,strlen($str)); // call the function.
輸出:
#php a.phphey hye ehy eyh yeh yhe
添加回答
舉報
0/150
提交
取消