# 647. Palindromic Substrings
Given a string, your task is to count how many palindromic substrings in this string.
The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters.
Example 1:
Input: "abc"
Output: 3
Explanation: Three palindromic strings: "a", "b", "c".
Example 2:
Input: "aaa"
Output: 6
Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
# Solution
Approach 1: DP in O(N^2)
-- start searching for palindromes from short to long ones, using O(N^2)
to store existing palindromes found.
Approach 2: expanding from a center, O(1)
space and O(N^2)
time.
Approach 3: Manacher's Algorithm (?)
# Code (Python)
Approach 1:
def countSubstrings(self, s: str) -> int:
# DP in O(N^2) -- start searching for palindromes from short to long ones, using O(N^2) to store existing palindromes found
if not s:
return 0
palindromes = set([char for char in s])
count = len(s)
for span in range(1, len(s)):
for start in range(len(s) - span): # while start + span < len(s)
if s[start] == s[start+span] and (span == 1 or s[start+1:start+span] in palindromes):
count += 1
palindromes.add(s[start:start+span+1])
return count
Approach 2:
def countSubstrings(self, s: str) -> int:
# expanding from a center, O(1) space and O(N^2) time
if not s:
return 0
count = 0
for center in range(2 * len(s) - 1): # each letter and each space in between them
left = center // 2
right = left + center % 2 # right == left if center is on the letter, otherwise right == left + 1
while left >= 0 and right < len(s) and s[left] == s[right]:
count += 1
left -= 1
right += 1
return count
# Code (C++)
Approach 1:
Approach 2: