Palindromic Substrings medium
Problem Statement
Given a string s
, return the number of palindromic substrings in it.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: s = "abc" Output: 3 Explanation: Three palindromic strings: "a", "b", "c".
Example 2:
Input: s = "aaa" Output: 6 Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
Steps
The core idea is to iterate through the string and for each character, check for palindromes expanding outwards:
-
Initialization: Create a counter
count
to store the number of palindromic substrings, initialized to 0. -
Iteration: Iterate through each character of the string
s
using a loop. -
Odd Length Palindromes: For each character, consider it as the center of a potential odd-length palindrome. Expand outwards from the center, checking if the characters at positions
i-k
andi+k
are equal. Incrementk
until you find unequal characters or reach the string boundaries. Incrementcount
for each palindrome found. -
Even Length Palindromes: For each character (except the last), consider the characters at positions
i
andi+1
as the center of a potential even-length palindrome. Expand outwards from this center, checking if the characters at positionsi-k
andi+k+1
are equal. Incrementk
until you find unequal characters or reach the string boundaries. Incrementcount
for each palindrome found. -
Return: After iterating through all characters, return the final
count
.
Explanation
The algorithm efficiently checks for all possible palindromic substrings without redundant checks. By expanding outwards from the center of potential palindromes (both odd and even lengths), we ensure that every palindrome is counted exactly once. The use of two nested loops ensures that all possible centers and expansions are considered.
Code
def countSubstrings(s):
"""
Counts the number of palindromic substrings in a given string.
Args:
s: The input string.
Returns:
The number of palindromic substrings.
"""
n = len(s)
count = 0
for i in range(n):
# Odd length palindromes
l, r = i, i
while l >= 0 and r < n and s[l] == s[r]:
count += 1
l -= 1
r += 1
# Even length palindromes
l, r = i, i + 1
while l >= 0 and r < n and s[l] == s[r]:
count += 1
l -= 1
r += 1
return count
Complexity
- Time Complexity: O(n^2), where n is the length of the string. This is because we have nested loops that iterate through all possible centers and expansions of palindromes.
- Space Complexity: O(1). The algorithm uses a constant amount of extra space.