647. Palindromic Substrings
Description
Solution
class Solution:
def expand_around_center(self, s: str, 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
def countSubstrings(self, s: str) -> int:
if len(s) == 1:
return 1
count = 0
for index in range(len(s)):
# we need to consider the two cases:
# i. odd length substrings where the mid char is one letter (i.e. "aba")
# ii. even length substrings where there are two mid characters (i.e. "abba")
count += self.expand_around_center(s, index, index)
count += self.expand_around_center(s, index, index + 1)
return count
"""
"a"
"aa"
"ab"
"abc"
"aaa"
"abba"
"aba"
"abaca"
"abbba"
"ababa"
"""Last updated