最长回文子串-中心扩散法
作者:互联网
var longestPalindrome = function (s) {
const strArr = []
const len = s.length
if (len < 2) return s
for (let i = 0; i < len; i++) {
let j = 0, k = 0
while (s[i - j] && s[i + j] && s[i - j] === s[i + j]) {
j++
}
strArr.push(s.slice(i - j + 1, i + j))
j = 0
while (s[i + 1] && s[i + 1] === s[i] && s[i - k] && s[i + 1 + k] && s[i - k] === s[i + 1 + k]) {
k++
}
strArr.push(s.slice(i - k + 1, i + k + 1))
k = 0
}
return strArr.sort((a, b) => {
return b.length - a.length
})[0]
};
console.log(longestPalindrome('bb'));
console.log(longestPalindrome('bab'));
console.log(longestPalindrome('b'));
console.log(longestPalindrome('baba'));
标签:子串,console,log,longestPalindrome,strArr,length,&&,扩散,回文 来源: https://blog.csdn.net/nishiweiyj/article/details/116304346