Leetcode 647. Palindromic Substrings JavaScript Solution

chefvivica
2 min readSep 13, 2020

Problem Description

Given a string, your task is to count how many palindromic substrings in this string.

The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters.

Example 1:

Input: "ABCBA"
Output: 7
Explanation: Three palindromic strings: "A", "B", "C", "B", "A", "BCB", "ABCBA".

Example 2:

Input: "AAA"
Output: 6
Explanation: Six palindromic strings: "A", "A", "A", "AA", "AA", "AAA".

Note:

  1. The input string length won’t exceed 1000.

The Solution:

Runtime : 76 ms .

Memory Usage: 37.1MB.

With this solution, we used two pairs of two pointers to traverse the string.

Let’s use two example to see how it works:

Note: below “l” represents left pointer, “r” represents right pointer

By using those four pointers, so i as the leader will traverse each letter since each letter is palindromic substrings, j will be in charge of the next letter of i to check the palindromic substrings which length are 2, left and right pointer will traverse the neighbors, so they will be in charge of the palindromic substrings which length are greater than 2.

Hope this blog is helpful for you. Thank you for reading.

--

--