给定一个字符串 s,找到 s 中最长的回文子串。你能够假设 s 的最大长度为 1000。
(具体要求请看5. 最长回文子串)php
参考了各路大神的解题思路,就这种我感受比较容易理解一点,因此就采用了中心扩展算法,等我再好好看看马拉车算法再和你们分享吧。
首先要了解回文的特色,它是关于中心对称的,这样的对称分为两种状况,一种的长度为奇数的字符串,一种是长度为偶数的字符串,根据这个特色,就能够分别比较中心两侧对应的字符,经过判断两侧对应字符是否相同来得出当前判断的子串是否为回文,代码以下:算法
class Solution { protected $len = 0; // 字符串长度 protected $start = 0; // 起始位置 protected $length = 0; // 截取长度 /** * @param String $s * @return String */ public function longestPalindrome($s) { $this->len = strlen($s); for ($i = 0; $i < $this->len; $i++) { // 若是起始位置 + 截取长度 = 字符串长度,就不须要继续循环下去,由于能够肯定当前长度是最长的 if ($this->start + $this->length >= $this->len) break; $this->expandAroundCenter($s, $i, $i); // 状况 1: aba $this->expandAroundCenter($s, $i, $i + 1); // 状况 2: bb } // 使用 substr 函数,截取相应的字符串 return substr($s, $this->start, $this->length); } /** * @param String $str * @param Integer $left * @param Integer $right */ protected function expandAroundCenter($str, $left, $right) { // 这里判断左右两边对应字符是否相等,若是相等,left-1,right+1,继续比较 while ($left >= 0 && $right < $this->len && $str[$left] === $str[$right]) { $left--; $right++; } // 当上面循环结束,也就是找到了一个回文子串 // temp 是子串的长度 $temp = $right - $left - 1; // 与 length 比较,看当前找到的子串是不是较长的那个, // 若是是,就给 start 和 length 赋值 if ($this->length < $temp) { $this->start = $left + 1; $this->length = $temp; } } }