const loopCompare = (leftIndex, rightIndex, arr, workStorage) =>{
if(arr[leftIndex] === arr[rightIndex]){
workStorage.unshift(arr[leftIndex])
workStorage.push(arr[rightIndex])
}
if(arr[leftIndex - 1] && arr[rightIndex + 1]){
loopCompare(leftIndex - 1, rightIndex + 1, arr, workStorage)
}
return;
}
const getStrLen = (str) =>{
const arr = str.split('');
let res = {};
if(arr.length === 1 || arr.length === 0){
return str
}
arr.map((char, index) =>{
let workStorage = {
o: [],
j: []
}
if(arr[index + 1] && char === arr[index + 1]){//偶数对称
loopCompare(index, index+1, arr, workStorage.o)
}
if(arr[index -1] && arr[index + 1] && (arr[index -1] === arr[index + 1])){//奇数对称
workStorage.j.push(char)
loopCompare(index-1, index+1, arr, workStorage.j)
}
if(workStorage.o.length === 0 && workStorage.j.length === 0){
workStorage.j.push(char)
}
res[index] = {
workStorage: workStorage.j.length > workStorage.o.length ? workStorage.j : workStorage.o,
str: workStorage.j.length > workStorage.o.length ? workStorage.j.join('') : workStorage.o.join(''),
length: workStorage.j.length > workStorage.o.length ? workStorage.j.length : workStorage.o.length
}
})
const max = Object.values(res).reduce((max, c) =>max?.length > c?.length ? max : c)
return max.str
}
console.log(getStrLen('abbaccccccca'))
网友评论