我想编写一个代码,在数组末尾找到与数组开头相同的最大字符序列.
但我不知道如何用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);