DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 66

The task is to count the number of substrings in a palindromic string.

The boilerplate code

function countPalindromicSubstr(str) {
  // your code here
}
Enter fullscreen mode Exit fullscreen mode

Each palindrome has a center. There are two kinds of centers: one with a single character(for odd-length palindromes), and a gap between 2 characters(for even-length palindromes).

For each center, we look left and right at the same time. If both characters match, it's a palindrome. Count it, move one step further out on both sides and keep going until the characters stop matching or the end of the string is reached.

let count = 0;


  function expand(left, right) {
    while (left >= 0 && right < str.length && str[left] === str[right]) {
      count++;
      left--;
      right++;
    }
  }
Enter fullscreen mode Exit fullscreen mode

Repeat for every possible center

for (let i = 0; i < str.length; i++) {
    expand(i, i);
    expand(i, i + 1);
  }
Enter fullscreen mode Exit fullscreen mode

The final code

function countPalindromicSubstr(str) {
  // your code here
  let count = 0;

  function expand(left, right) {
    while(left >= 0 && right < str.length && str[left] === str[right]) {
      count++;
      left--;
      right++;
    }
  }
  for(let i = 0; i < str.length; i++) {
    expand(i, i);
    expand(i, i + 1);
  }
  return count;
}
Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)