字符串最长重复子串

2022-05-24  本文已影响0人  Rohn

题目:获取字符串最长重复的子字符串

input:qweertqwer
output:qwe

input:qwertyuie
output:e

input:abcdefefefef
output:efef

<?php

$string = 'abcdefefefef';
var_dump(getSubStr($string));

function getSubStr($string){

    $stringLen = strlen($string);
    //最长情况为半长字符串
    for($l=floor($stringLen/2);$l>0;$l--){
        for($i=0;$i<($stringLen-$l)&&($i+2*$l)<=$stringLen;$i++){
            //最长子串
            $res = substr($string, $i, $l);
            //剩下的字符串
            $left = substr($string, $i+$l);
            if(strpos($left,$res)!==false){
                return $res;
            }
        }
    }
    return false;
}
上一篇 下一篇

猜你喜欢

热点阅读