Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the maximum sequence of characters at the end of an array that are the same as the beginning of the array?

I want to write code that finds the maximum sequence of characters at the end of an array that are the same as the beginning of the array.

But I dont know how I can do it with PHP?

For example:

Input = [a,b,c,e,r,t,x,s,b,a,b,c] 
Output = [a,b,c]

(because the elements a,b,c are both at the beginning and end of the array and they represent the maximum sequence of such characters)

like image 766
sunny Avatar asked Mar 10 '23 08:03

sunny


1 Answers

Note: This will work perfectly for this kind of array, where we have array of strings, it does not work for nested array.

Try this code snippet here

<?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);
like image 125
Sahil Gulati Avatar answered Mar 11 '23 21:03

Sahil Gulati