我不太确定在这里使用这个词,如果我使用错误的术语,请原谅。
我正在尝试创建一个函数来获取字符串的下一个排列,给出当前字符串和一串允许的字符。
例如
<pre>
<?php
$current = '';
$allowed = 'ab';
function next(&$current, &$allowed) {
// This is where I need help
}
echo next($current, $allowed) . "\n";
echo next($current, $allowed) . "\n";
echo next($current, $allowed) . "\n";
echo next($current, $allowed) . "\n";
echo next($current, $allowed) . "\n";
echo next($current, $allowed) . "\n";
echo next($current, $allowed) . "\n";
echo next($current, $allowed) . "\n";
echo next($current, $allowed) . "\n";
echo next($current, $allowed) . "\n";
echo next($current, $allowed) . "\n";
echo next($current, $allowed) . "\n";
echo next($current, $allowed) . "\n";
echo next($current, $allowed) . "\n";
echo next($current, $allowed) . "\n";
应该返回
a
b
aa
ab
ba
bb
aaa
aab
aba
abb
baa
bab
bba
bbb
aaaa
......等等
我正在尝试在PHP和JavaScript中执行此操作,因此我将非常感谢您使用这两种语言提供帮助。
答案 0 :(得分:0)
function nextPermutation(&$current, $allowed) {
if (empty($current)) {
$current = $allowed[0];
} else {
for ($i = strlen($current) - 1; $i >= 0; $i--) {
$index = strpos($allowed, $current[$i]);
if ($index < strlen($allowed) - 1) {
$current[$i] = $allowed[$index + 1];
break;
} else {
$current[$i] = $allowed[0];
if ($i == 0) {
$current = $allowed[0] . $current;
break;
}
}
}
}
return $current;
}