<?php
/**
* 最长回文子串
*
* User: hihone
* Date: 2019/2/1
* Time: 10:16
* Description:
* 给定一个字符串 $string,找到 $string 中最长的回文子串。
* 回文串就是正着读和反着读都一样的字符串。
*/
class Solution
{
public function longestPalindrome($string)
{
$len = strlen($string);
if (empty($string) || empty($len)) return '';
$start = 0;
$end = 0;
for ($i = 0; $i < $len; $i++) {
$len1 = $this->expandAroundCenter($string, $i, $i);
$len2 = $this->expandAroundCenter($string, $i, $i + 1);
$max = max($len1, $len2);
if ($max > $end - $start) {
$start = $i - intval(($max - 1) / 2);
$end = $i + intval($max / 2);
}
}
$subStrLen = $end - $start + 1;
return substr($string, $start, $subStrLen);
}
/**
* @param $string
* @param $l
* @param $r
*
* @return int
*/
private function expandAroundCenter($string, $l, $r)
{
while ($l >= 0 && $r < strlen($string) && $string[$l] == $string[$r]) {
$l--;
$r++;
}
return $r - $l - 1;
}
}
$s = new Solution();
$str = 'cbbd';
echo $s->longestPalindrome($str);
网友评论