// 中心扩展函数
center_expand = (s, left, right) => {
while (left >= 0 && right < s.length && s.charAt(left) == s.charAt(right)) {
left--;
// 向左边扩展
right++;
// 向右边扩展
}
const len = right - left - 1;
// 记录长度
return len;
};
// 查找最长回文子串
longestPalindrome = (s) => {
const len = s.length;
if (len <= 1) return s;
// 字符串为空或者长度等于1,直接返回
let max = 0;
// 记录字符串最大值
let ret = null;
// 存放回文
for (let i = 0; i < len; i++) {
const len1 = this.center_expand(s, i, i);
// 以i为中心,i为左,i也为右
const len2 = this.center_expand(s, i, i + 1);
// 以(i, i + 1)为中心,i为左,i+1为右
const len3 = Math.max(len1, len2);
// 取出最大长度
if (len3 > max) {
const L = i - (len3 - 1) / 2;
// 最大回文长度的左边
const R = i + len3 / 2;
// 最大回文长度的右边
max = len3;
// 回文的最大长度
ret = s.substring(L, R + 1);
// 将回文存放在ret中
}
}
return ret;
};
最长回文子串
最新推荐文章于 2022-11-18 09:37:48 发布