【发布时间】:2017-09-12 18:43:43
【问题描述】:
我想编写代码,在数组末尾找到与数组开头相同的最大字符序列。
但我不知道如何用 PHP 做到这一点?
例如:
Input = [a,b,c,e,r,t,x,s,b,a,b,c]
Output = [a,b,c]
(因为元素a,b,c在数组的开头和结尾都代表了这些字符的最大序列)
【问题讨论】:
标签: php arrays duplicates subset array-filter
我想编写代码,在数组末尾找到与数组开头相同的最大字符序列。
但我不知道如何用 PHP 做到这一点?
例如:
Input = [a,b,c,e,r,t,x,s,b,a,b,c]
Output = [a,b,c]
(因为元素a,b,c在数组的开头和结尾都代表了这些字符的最大序列)
【问题讨论】:
标签: php arrays duplicates subset array-filter
sunny,我为你准备了一份好东西!
方法:
$found=false; // declare default outcome
for($x=1,$max=sizeof($data); $x<=$max; ++$x){ // this allows "overlap"
if(array_slice($data,0,$x)===array_slice($data,-$x)){ // compare start to end
$found=true; // declare a match has occurred
}elseif($found){ // this iteration is no match
--$x; // rewind to successful match
break;
}
}
var_export($found?array_slice($data,0,$x):"No match"); // output the result
输入和输出:
$data=['a','b','c','e','r','t','x','s','b','a','b','c']; // ['a','b','c']
$data=['n','o','p','e']; // No Match
$data=['r','a','c','e','c','a','r']; // ['r']
$data=['a','a','b','a','a']; // ['a','a']
解释:
尽可能避免使用基于正则表达式的解决方案更为有效和明智。此外,我设法编写了一个将输入保持为数组形式的解决方案(避免不必要的转换)。
array_slice() 是这个答案的明显英雄。随着$x 的增加,两个array_slice() 调用保持同步,允许进行简单的条件比较。
$max 设置为迭代整个数组,并欢迎数组内“重叠”的可能性。如果您不希望有任何“重叠”的机会,您可以使用$max=floor(sizeof($data)/2)
找到匹配后,一旦出现不匹配,循环就会中断,并显示正确的输出。
问题扩展...
回文匹配——你可以通过添加array_reverse()轻松调整我上面的方法来匹配镜像序列。
方法:
$found=false;
for($x=1,$max=sizeof($data); $x<=$max; ++$x){
if(array_slice($data,0,$x)===array_reverse(array_slice($data,-$x))){ // only change
$found=true;
}elseif($found){
--$x;
break;
}
}
var_export($found?array_slice($data,0,$x):"No match");
输入和输出:
$data=['a','b','c','e','r','t','x','s','b','a','b','c']; // No Match
$data=['n','o','p','e']; // No Match
$data=['r','a','c','e','c','a','r']; // ['r','a','c','e','c','a','r']
$data=['a','a','b','a','a']; // ['a','a','b','a','a']
【讨论】:
注意:这对于这种数组非常有效,我们有字符串数组,它不适用于嵌套数组。
<?php
ini_set('display_errors', 1);
$data = array("a","b","c","e","r","t","x","s","b","a","b","c");
$string= implode("", $data);//converting array to string.
for($x=strlen($string)-1;$x>=0;$x--)
{
//matching substring from the end of string.
if(preg_match("/".substr($string, 0,$x)."$/",$string)==true)
{
$string= substr($string, 0,$x);
break;
}
}
$result=str_split($string);
print_r($result);
【讨论】:
我希望这段代码能正常工作:
<?php
$Input = array('a','b','c','e','r','t','x','s','b','a','b','c');
$len=count($Input);
$j=$len-1;
$count=0;
$s=0;
$k=$n=0;
$a[$len/2];
for($i=0;$i<$len;$i++)
{
if($Input[$i]!=$Input[$j]){
$j--;
$i--;
}
if($Input[$i]==$Input[$j]){
$count++;
$a[$n]=$Input[$j];
$n++;
if($k==$j)
{
$s++;
break;
}
$k=$j;
if($j!=$len-1)
$j++;
else
break;
}
}
if($s!=0)
echo "sequence not present";
else
{
echo "<br>sequence present <br>";
$len2=count($a);
for($p=0;$p<$len2;$p++)
echo" ".$a[$p];
}
?>
【讨论】: