// 暴力破解 O(n^3)
var longestPalindrome = function(s) {
var result = []
const sArr = s.split('')
for(let i=0;i<sArr.length;i++){
for(let j=0;j<sArr.length;j++){
let tempArr = sArr.slice(i,j)
let flag = true
for(let k=0;k<tempArr.length/2;k++){
if(tempArr[k] !== tempArr[tempArr.length-1-k]){
flag = false
}
}
if(flag && tempArr.length){
if(result.length < tempArr.length){
result = tempArr
}
}
}
}
return result
};
// 中间向两边延伸O(n^2)
var longestPalindrome = function (s) {
var result = ""
for (let i = 0; i < s.length; i++) {
let temp = ""
let temp1 = isPalindrome(s, i-1, i+1)
let temp2 = isPalindrome(s, i, i+1)
temp = temp1.length > temp2.length ? temp1 : temp2
if (result.length <= temp.length) {
result = temp
}
}
if (result == "") {
return s.charAt(0)
}
return result
};
var isPalindrome = function (s, low, high) {
let result = ""
while (low >= 0 && high < s.length) {
if (s.charAt(low) == s.charAt(high)) {
const temp = s.substring(low, high + 1)
if (result.length <= temp.length) {
result = temp
}
low--
high++
}else{
break
}
}
return result
}
还可以进行优化对某些判断获得字符传进行缓存
网友评论