SDE & MLE Prep

647. Palindromic Substrings

Problem

Count the substrings of s that are palindromes; substrings at different positions count separately even if equal.

Example: "abc" → 3; "aaa" → 6

Constraints: length ≤ 1000.

Same centre expansion; every successful expansion step is one more palindrome.

Complexity: O(n²).

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