LeetcodeSep 14, 2025

Palindromic Substrings

Hazrat Ali

Leetcode

A string is a palindrome when it reads the same backward as forward.

substring is a contiguous sequence of characters within the string.

 

Example 1:

Input: s = "abc"
Output: 3
Explanation: Three palindromic strings: "a", "b", "c".

Example 2:

Input: s = "aaa"
Output: 6
Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".

Solution
/**
 * @param {string} s
 * @return {number}
 */
const countSubstrings = s => {
  const extendPalindrome = (s, left, right) => {
    while (left >= 0 && right < s.length && s[left] === s[right]) {
      count++;
      left--;
      right++;
    }
  };

  if (!s || s.length === 0) {
    return 0;
  }

  let count = 0;

  for (let i = 0; i < s.length; i++) {
   
    extendPalindrome(s, i, i);
    extendPalindrome(s, i, i + 1);
  }

  return count;
};





Comments