Given a string s
, return the number of palindromic substrings in it. A string is a palindrome when it reads the same backward as forward. A substring is a contiguous sequence of characters within the string.
s
will be of length at most 1000
.s
consists of lowercase English letters only.s = "abc"
3
because a
, b
, and c
are palindromic.s = "aaa"
6
because a
, a
, a
, aa
, aa
, aaa
are palindromic.We’ll use the “Expand Around Center” strategy. The idea is to consider each possible center for odd and even-length palindromes and attempt to expand outward as long as the substring remains a palindrome.
count
to 0.s
, treating each character as the center of an odd-length palindrome.Since each center expansion takes O(N) time in the worst case, and there are 2N - 1
such centers (each character and space between characters), the overall time complexity is:
s
.Here’s the implementation of the strategy described:
def countSubstrings(s: str) -> int:
def expand_around_center(left: int, right: int) -> int:
count = 0
while left >= 0 and right < len(s) and s[left] == s[right]:
count += 1
left -= 1
right += 1
return count
count = 0
for i in range(len(s)):
# Count odd-length palindromic substrings
count += expand_around_center(i, i)
# Count even-length palindromic substrings
count += expand_around_center(i, i + 1)
return count
# Example Usage
print(countSubstrings("abc")) # Output: 3
print(countSubstrings("aaa")) # Output: 6
This solution efficiently counts the palindromic substrings using the expand-around-center approach, ensuring a thorough check of all possible palindromes within the given string s
.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?