美文网首页
找到最长的回文子串

找到最长的回文子串

作者: 红酒煮咖啡 | 来源:发表于2022-09-27 10:02 被阅读0次
    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'))
    
    

    相关文章

      网友评论

          本文标题:找到最长的回文子串

          本文链接:https://www.haomeiwen.com/subject/ofsfartx.html