关于javascript:LeetCode-题解|5-最长回文子串

6次阅读

共计 720 个字符,预计需要花费 2 分钟才能阅读完成。

回文是指一个字符串不论从左往右看还是从右往左看都是一样的
那么就会有两种状况:1. 复数回文,2. 单数回文

双指针解法

利用两个指针,指针内的字符串就是匹配到的回文字符串

function longestPalindrome(str) {
  // 最终后果
  let result = "";
  for (let index = 0; index < str.length; index++) {
    // 回文核心是复数(本人)时,即复数回文
    findRepeat(index, index);
    // 回文核心是单数时,即单数回文
    findRepeat(index, index + 1);
  }
  // 匹配传入指针对应的最大回文字符串
  function findRepeat(leftIndex, rightIndex) {
    while (
      leftIndex >= 0 &&
      rightIndex < str.length &&
      str[rightIndex] === str[leftIndex]
    ) {
      leftIndex--;
      rightIndex++;
    }
    // 这里要留神:下面的 while 循环会在条件不成立时终止,所以 leftIndex 的最终值 多减了 1,rightIndex 的最终值 多加了 1
    // slice 左闭右开的个性,leftIndex 又多减了 1 所以 leftIndex 要 + 1 解决,rightIndex 要 - 1 解决,而 rightIndex 自身就多加了 1 所以互相对消
    const replaceStr = str.slice(leftIndex + 1, rightIndex);
    if (result.length < replaceStr.length) {result = replaceStr;}
  }
  return result;
}

本文由一文多发经营工具平台 EaseWriting 公布

正文完
 0