最长回文子串
暴力枚举法
const forceMethod = (str) => {
if (str.length < 2) return str
let cur = 0
let max = 1
const judge = (s) => {
let l = 0
let r = s.length - 1
while (l < r) { // 到l > r的时候会跳出循环
if (s[l] !== s[r]) {
return false
}
l++
r--
}
return true
}
for (let i = 0; i < str.length; i++) {
for (let j = i + 1; j < str.length; j++) {
let curStr = str.slice(i, j + 1)
if (judge(curStr) && curStr.length > max) {
cur = i
max = curStr.length
}
}
}
console.log(cur, max)
return str.substr(cur, max)
}
中心扩散法
const longestPalindrome = str => {
if (str.length < 2) return str
let start = 0
let maxLen = 1
// 判断函数
const judge = (left, right) => {
while (left >= 0 && right < str.length && str[left] === str[right]) { // 说明满足条件
if (right - left + 1 > maxLen) {
maxLen = right - left + 1
start = left
}
left--
right++
}
}
for (let i = 0; i < str.length; i++) {
judge(i - 1, i + 1) // 奇数
judge(i, i + 1) // 偶数
}
return str.slice(start, start + maxLen)
}