dp
palindrome
]
Leetcode 0647. Palindromic Substrings
https://leetcode.com/problems/palindromic-substrings
Each palindrome has center: this is either some symbol or place between symbols. Let us for more simplicity define center by pair or elements i, j
. If center is symbol, then it will be (i, i)
; if center is between symbols it will be (i, i+1)
. All we need to do now is to expand around each of the possible centers and iterrupt when we meet different symbols. In the end return sum of number of found palindromes.
Complexity: time complexity is O(n^2)
, because we have 2n-1
possible centers and we can expand upto O(n)
length. Space complexity is O(n)
.
Remark Yes, I am aware, that there exists O(n)
Manacher algorithm, but it is much more difficult to code and explain how it works. If for some reason you will need it on competition you can quickly google it and use.
class Solution:
def countSubstrings(self, s):
def helper(i, j):
while i >= 0 and j < len(s) and s[i] == s[j]:
i, j = i - 1, j + 1
return (j-i)//2
return sum(helper(k,k) + helper(k,k+1) for k in range(len(s)))
If you like the solution, you can upvote it on leetcode discussion section: Problem 0647