Back to Problem
Official 297 views

Editorial: Count Palindromic Substrings

by admin ·

31

1 Intuition

Every palindrome expands from a center — a character or a gap.

2 Approach

Try all 2n − 1 centers and expand outward while the ends match, counting each step.

3 Complexity Analysis

Time O(n²), Space O(1).

4 Solution Code

class Solution:
    def countSubstrings(self, s: str) -> int:
        count = 0
        for center in range(2 * len(s) - 1):
            lo, hi = center // 2, center // 2 + center % 2
            while lo >= 0 and hi < len(s) and s[lo] == s[hi]:
                count += 1
                lo -= 1
                hi += 1
        return count

5 Code Walkthrough

The reference solution below implements the approach step by step.