我正在尝试查找给定字符串的所有可能的2个字母组合。有没有更快的方法,比按位置应用子串位置然后再次调用函数?
以下是我正在尝试的内容:
function permute($str) {
if (strlen($str) < 2) {
return array($str);
}
$permutations = array();
$tail = substr($str, 1);
foreach (permute($tail) as $permutation) {
$length = strlen($permutation);
for ($i = 0; $i <= $length; $i++) {
$permutations[] = substr($permutation, 0, $i) . $str[0] . substr($permutation, $i);
}
}
return $permutations;
}
$str = "tone";
$permutations = array_unique(permute($str));
$str1 = substr_replace($str, "", 1,2);
$permutations = array_unique(permute($str1));
鉴于上面的字符串“音调”,我想得到答案:
to
tn
te
on
oe
ne
ot
nt
et
no
eo
en
答案 0 :(得分:2)
如果你想使用substr
function str2array($string) {
$strArray = [];
for ($i = 0; $i < strlen($string); $i++) {
$strArray[] = substr($string, $i, 1);
}
return $strArray;
}
但请改用str_split
。
$string = 'tone';
$strArray = str_split($string);
foreach ($strArray as $key => $char1) {
$strArray2 = $strArray;
unset($strArray2[$key]);
foreach ($strArray2 as $char2) {
$permutations[] = $char1 . $char2;
}
}
//EDIT: adding array_unique in case of dupes
$uniquePermutations=array_unique($permutations);
print_r($uniquePermutations);
阵 ( [0] =&gt;至 [1] =&gt; TN [2] =&gt; TE [3] =&gt; OT [4] =&gt;上 [5] =&gt; OE [6] =&gt; NT [7] =&gt;没有 [8] =&gt; NE [9] =&gt;等 [10] =&gt; EO [11] =&gt;恩 )