DevPath

← All problems

Palindromic Substrings

Medium dynamic-programming · strings

Description

Return the number of palindromic substrings (substrings at different positions count separately).

Constraints

1 <= length <= 1000

Examples

Input: s = "aaa"

Output: 6

Hints (1)
  • Expand around every centre (2n-1 centres).

Solutions

Expand around centres. · Time O(n^2) · Space O(1)

func countSubstrings(s string) int {
    n := len(s)
    count := 0
    for center := 0; center < 2*n-1; center++ {
        l := center / 2
        r := l + center%2
        for l >= 0 && r < n && s[l] == s[r] {
            count++
            l--
            r++
        }
    }
    return count
}

Create a free account to submit solutions, track progress and save problems.

Create account