【发布时间】:2012-10-03 23:59:17
【问题描述】:
我需要一个可以执行以下操作的函数:
如果我有一个像 "2 1 3 6 5 4 8 7" 这样的字符串,我必须按照一些规则在成对的数字之间插入破折号。
规则很简单。
如果第一个数字小于后面的数字,则在两个数字之间添加一个破折号。做所有可能的组合,如果一对已经有破折号,那么它旁边的空格就不能有破折号。
基本上我对上述字符串的结果是
2 1-3 6 5 4 8 7
2 1-3 6 5 4-8 7
2 1 3-6 5 4 8 7
2 1 3-6 5 4-8 7
2 1 3 6 5 4-8 7
我确实创建了一个函数来执行此操作,但我认为它非常缓慢,我不想用它来污染您的想法。如果可能的话,我想知道你们是怎么想的,甚至一些伪代码或代码也会很棒。
编辑 1: 这是我到目前为止的代码
$string = "2 1 3 6 5 4 8 7";
function dasher($string){
global $dasherarray;
$lockcodes = explode(' ', $string);
for($i = 0; $i < count($lockcodes) - 1; $i++){
if(strlen($string) > 2){
$left = $lockcodes[$i];
$right = $lockcodes[$i+1];
$x = $left . ' ' . $right;
$y = $left . '-' . $right;
if (strlen($left) == 1 && strlen($right) == 1 && (int)$left < (int)$right) {
$dashercombination = str_replace($x, $y, $string);
$dasherarray[] = $dashercombination;
dasher($dashercombination);
}
}
}
return array_unique($dasherarray);
}
foreach(dasher($string) as $combination) {
echo $combination. '<br>';
}
【问题讨论】:
-
请向我们展示您已经完成的工作并解释您认为其中有什么问题。不要害怕“用它来玷污我们的想法”,这里有足够经验的人来确保这样的事情不会发生。但是 - 我们确实喜欢看到提问者的努力,这给了我们动力,他们确实自己尝试过(而不是问陌生人作为解决问题的第一次尝试),并且答案更有可能对你更好 - 因为它将引导您找到解决方案。
-
我认为它的错误在于我想避免递归并且可能不调用 str_replace。我尝试用 $string[($*2)-1] = '-' 简单地替换 str_replace ,但我没有得到预期的结果。
-
我编辑了条目 amit。感谢您查看此内容。
标签: php string recursion replace