In this approach, consider each character in the string, and each pair of consecutive characters as the center of potential palindromes. From each center, expand outward until the substring is no longer a palindrome. This allows for both odd-length and even-length palindromes to be discovered.
Time complexity: O(n^2), where n is the length of the string.
Space complexity: O(1), since we're only using a few auxiliary variables.
1def count_substrings(s: str) -> int:
2 count, n = 0, len(s)
3 for center in range(2 * n - 1):
4 left = center // 2
5 right = left + center % 2
6 while left >= 0 and right < n and s[left] == s[right]:
7 count += 1
8 left -= 1
9 right += 1
10 return count
11
12s = "aaa"
13print(count_substrings(s)) # Output: 6
This Python implementation mirrors the previous strategies, expanding around center points in the string to find all palindromic substrings.
Utilizing Dynamic Programming, we can store results of previously calculated palindromic substrings in a table. If we know a substring between two indices is a palindrome, we can extend this information to build larger palindromes, reducing redundant checks.
Time complexity: O(n^2), Space complexity: O(n^2), due to the storage of the DP table.
1def count_substrings(s: str) -> int:
2 n = len(s)
3 dp = [[False] * n for _ in range(n)]
4 count = 0
5 for i in range(n - 1, -1, -1):
6 for j in range(i, n):
7 dp[i][j] = (s[i] == s[j] and (j - i < 3 or dp[i + 1][j - 1]))
8 if dp[i][j]:
9 count += 1
10 return count
11
12s = "aaa"
13print(count_substrings(s)) # Output: 6
This Python solution uses a similar DP table to store whether substrings are palindromes and iteratively build solutions for larger substrings based on these results.