我想编写代码来查找数组末尾的最大字符序列,它们与数组的开头相同。如何查找与数组开头相同的数组末尾的最大字符序列?
但我不知道如何用PHP做到这一点?
例如:
Input = [a,b,c,e,r,t,x,s,b,a,b,c]
Output = [a,b,c]
(因为a,b,c
在阵列的开头和结尾都和它们代表这样的最大字符序列中的元素)
我想编写代码来查找数组末尾的最大字符序列,它们与数组的开头相同。如何查找与数组开头相同的数组末尾的最大字符序列?
但我不知道如何用PHP做到这一点?
例如:
Input = [a,b,c,e,r,t,x,s,b,a,b,c]
Output = [a,b,c]
(因为a,b,c
在阵列的开头和结尾都和它们代表这样的最大字符序列中的元素)
注:这将工作对于这种有数组的字符串来说非常完美,它不适用于嵌套数组。
<?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];
}
?>
阳光明媚,我有一个很好的为您服务!
方法:
$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']