var longestPalindrome = function(s) {
if(s.length<2){
return s
}
let newString = '#'
for(let i=0; i<s.length; i++){
newString+=s[i]+'#'
}
let mid = Math.floor(newString.length/2);
let rightStand = mid + 1;
let leftStand = mid -1;
let max = 0;
let ans = '';
let canMax = newString.length;
const getMaxOrRenewMax = (stand, canMax) => {
let left = stand;
let right = stand;
let count = 1;
while(newString[--left] && newString[++right]){
if(newString[left]===newString[right]){
count+=2
}else{
break;
}
}
if(max < count){
max = count;
ans = newString.substring(left+1, right)
}
if(count ===canMax){
return ans.split('').filter(i=>i!=='#').join('')
}
}
const midMax = getMaxOrRenewMax(mid, canMax);
if(midMax) return midMax;
canMax-=2;
while(leftStand >= 0){
const leftMax = getMaxOrRenewMax(leftStand, canMax);
const rightMax = getMaxOrRenewMax(rightStand, canMax);
if(leftMax) return leftMax;
if(rightMax) return rightMax;
canMax-=2;
leftStand--;
rightStand++;
}
return ans.split('').filter(i=>i!=='#').join('');
};
Level
LeetCode Medium