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.
1#include <stdio.h>
2#include <string.h>
3
4int countSubstrings(char *s) {
5 int count = 0, n = strlen(s);
6 for (int center = 0; center < 2 * n - 1; ++center) {
7 int left = center / 2;
8 int right = left + center % 2;
9 while (left >= 0 && right < n && s[left] == s[right]) {
10 count++;
11 left--;
12 right++;
13 }
14 }
15 return count;
16}
17
18int main() {
19 char s[] = "aaa";
20 printf("%d\n", countSubstrings(s)); // Output: 6
21 return 0;
22}
The C solution uses two nested loops. The outer loop iterates over possible centers of palindromic substrings, which are twice the length of the string minus one (to account for centers in between characters for even-length palindromes). The inner loop expands from the center until a non-palindromic string is found.
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.