当前位置:网站首页>PHP design function getmaxstr to find the longest symmetric string in a string - [original]

PHP design function getmaxstr to find the longest symmetric string in a string - [original]

2022-06-26 04:20:00 Telkobe

Link to the original text

This is the first time I have encountered this problem , So handwriting is almost impossible for me , Because I have to debug on the machine repeatedly to get the final answer , Since I came back, I tried to write it on the computer , If there are shortcomings or simpler methods , Welcome to correct . The purpose of this problem is to write a function to find the symmetrical part of a string , Then get the longest string that meets the conditions , Like strings ‘ssabcddcba’, Then what meets the conditions is ‘abcddcba’, Let's go straight to the code .

$str='aa6aaslolsbcdeggedcbaiokabccbanh';
function getMaxStr($str){
    $s_data=str_split($str);
    $row=[];
    foreach($s_data as $key=>$vol){
        foreach($s_data as $k=>$v){
            if($k<$key) continue;
            if($vol==$v && $key!=$k){
                if(($key+$k)==1){
                    $row[]=substr($str,$key,2);
                }else{
                    $px=$key==0?$k+1:$k-$key;
                    $px=($px%2)==0?$px:($k-$key+1);
                    $px=$px/2;
                    for($s=1;$s<$px;$s++){
                        if($s_data[$key+$s]!=$s_data[$k-$s]) continue 2;
                    }
                    $row[]=substr($str,$key,($k-$key+1));
                }
            }
        }
    }
    return $row;
}
$r=getMaxStr($str);
print_r($r);

 

原网站

版权声明
本文为[Telkobe]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202180535384533.html