算法笔记7:回文子串

114 阅读1分钟

647.回文子串

这道题目想到了可以找中心点然后向两边展开,但是忘了考虑奇数长度和偶数长度,一开始想的是循环两遍。看了题解发现不需要循环两遍,但是得靠找规律,还是太年轻……

代码如下:

const countSubstrings = (s) => {
    const len = s.length;
    let count = 0;
    
    // through the observation, this is the boundary of the iterations
    for (let i = 0; i < 2 * len - 1; ++i) {
      let l = Math.floor(i / 2);
      let r = l + i % 2;
      while (l >= 0 && r < len && s[l] === s[r]) {
        l--;
        r++;
        count++;
      }
    }
    
    return count;
}