647. Number of palindromic substring
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".Note:
The input string length won't exceed 1000.
Thoughts:
Explanation by GeeksforGeeks (with extension problem to output all the substrings)
for loop with O(n^2) solution: having a pivot as a midpoint of palindrome and expand it in both directions to find all palindromes of even and odd lengths.
O(n) with Manacher’s algorithm
Code:
Special thanks to caihao0727mail for providing this solution.
Code: Interesting implementation using round-off
Code: Manacher's Algorithm: O(n) !
Special thanks to hellokenlee for providing this solution.
Last updated
Was this helpful?