Palindromic Substrings
Examples
Example 1:
Input: s = "abc"
Output: 3
Explanation:
Example 2:
Input: s = "aaa"
Output: 6
Explanation:
Example 1:
Input: s = "abc"
Output: 3
Explanation:
Example 2:
Input: s = "aaa"
Output: 6
Explanation:
Given a string s, return the number of substrings within s that are palindromes.
A palindrome is a string that reads the same forward and backward.
"a", "b", "c".
"a", "a", "a", "aa", "aa", "aaa". Note that different substrings are counted as different palindromes even if the string contents are the same.
1 <= s.length <= 1000s consists of lowercase English letters.Count palindromes by expanding around every center. For each index, expand for odd and even centers and add how many valid palindromes are found.
Every palindromic substring is determined by a center. Expanding from all centers counts each palindrome exactly once, so the total count is correct.
O(n^2)O(1)class Solution:
def countSubstrings(self, s: str) -> int:
def expand(l: int, r: int) -> int:
count = 0
while l >= 0 and r < len(s) and s[l] == s[r]:
count += 1
l -= 1
r += 1
return count
total = 0
for i in range(len(s)):
total += expand(i, i)
total += expand(i, i + 1)
return total