题目要求
给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。
(具体要求请看5. 最长回文子串)
解题思路
参考了各路大神的解题思路,就这种我感觉比较容易理解一点,所以就采用了中心扩展算法,等我再好好看看马拉车算法再和大家分享吧。
首先要了解回文的特点,它是关于中心对称的,这样的对称分为两种情况,一种的长度为奇数的字符串,一种是长度为偶数的字符串,根据这个特点,就可以分别比较中心两侧对应的字符,通过判断两侧对应字符是否相同来得出当前判断的子串是否为回文,代码如下:
代码
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; } } }
—-想了解更多的php相关异常处理怎么解决关注<计算机技术网(www.ctvol.com)!!>
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/phpttorial/106867.html