Leetcode 中等三 最长回文子串

最长回文子串:

php:

32ms。Manacher 算法实现:时间复杂度O(n)。

class Solution {

    /**
     * @param String $s
     * @return String
     */
    function longestPalindrome($s) {
        $new_str = "^#" . implode("#",str_split($s)) . "#$";
        $max_right = 0;
        $max_lp = '';
        $max_radius = 0;
        $center = 0;
        $r = [];
        for($i = 1;$i < strlen($new_str);$i++){
            $r[$i] = $max_right > $i ? min(($r[2*$center - $i]) , ($max_right - $i)) : 1;
            while($new_str[$i + $r[$i]] == $new_str[$i - $r[$i]]){
                $r[$i]++;
            }
            if(($r[$i] + $i) > $max_right){
                $center = $i;
                $max_right = $r[$i] + $i;
            }
            if($r[$i] > $max_radius){
                $max_radius = $r[$i];
                $max_lp = substr($new_str,$i - $r[$i] + 1, 2*$r[$i] - 1);
                $k = $i;
            }
        }
        return str_replace("#","",$max_lp);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_36688622/article/details/89134005