[5] 最长回文子串

复制代码
/**
 * @param {string} s
 * @return {string}
 */
var longestPalindrome = function (s) {
  let ll = s.length;
  let left = 0;
  let right = 1;
  let p = 0;

  while (p < ll - 1) {
    let new_left = p;
    let new_right = p;
    for (let i = p - 1; i >= 0; i--) {
      if (s.charAt(i) === s.charAt(new_left)) {
        new_left = i;
      } else {
        break;
      }
    }

    for (let i = p + 1; i < ll; i++) {
      if (s.charAt(i) === s.charAt(new_right)) {
        new_right = i;
      } else {
        break;
      }
    }

    p = new_right + 1;
    let forll = new_left;

    if (forll > ll - new_right - 1) {
      forll = ll - new_right - 1;
    }

    let j = 1;
    for (; j <= forll; j++) {
      if (s.charAt(new_left - j) !== s.charAt(new_right + j)) {
        break;
      }
    }

    new_left = new_left - j + 1;
    new_right = new_right + j - 1;

    if (right - left < new_right + 1 - new_left) {
      right = new_right + 1;
      left = new_left;
    }
  }

  return s.substring(left, right);
};
复制代码

 

posted @   人恒过  阅读(10)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本

阅读目录(Content)

此页目录为空

点击右上角即可分享
微信分享提示