JavaScript 题解

速度慢得爆炸💥

思路

  • 用一个辅助函数检查某一段是否是回文字符串,通过移动两边的索引坐标对比字符是否相等来判断
  • 首先我们知道至少最短的为 1,然后遍历每一个字符,再检查这个字符从最右边到当前的最长回文状态,得到最长的值之后直接跳出循环
  • 如果得到了一个超过剩下检查范围的最大值,则直接返回结果。

代码

const help = (str, i, j) => {
  if (str.length < 2) return true;
  while (i < j) {
    if (str[i] !== str[j]) {
      return false;
    }
    i++;
    j--;
  }
  return true;
};

const secretCut = (str) => {
  if (str.length === 1) return 1;

  let max = 1;
  for (let idx = 0; idx < str.length; idx++) {
    let end = str.length - 1;
    while (end > idx) {
      if (help(str, idx, end)) {
        max = Math.max(max, end - idx + 1);
        break;
      }
      end--;
    }
    if(max >= str.length - idx - 1) return max;
  }
  return max;
};

console.log(secretCut(readline()));