Given a string
Output: 3
Explanation: there are three palindromic substrings in the input string "a", "b" and "c".
Output: 6
Explanation: there are six palindromic substrings "a", "a", "a", "aa", "aa" and "aaa".
This problem is similar to
Contents
Solution - expand around center
In this approach, what we are going to do is, from every index in the string, we try to expand to the left and to the right and check whether the characters on both sides are same or not.
-
Create a helper method
expandAroundCenterHelper that takes parameters input strings , intl and intr left and right indexes to expand around and count number of palindromes found from that index.-
In the implementation of this method, create a variable
total to keep track of all palindromes found. -
We will then try to expand the palindromic substring using left and right indexes
l andr . -
While
l andr within the boundararies of input string's length, check character atl th index andr th indexes are same, that means we have found a palindrome, then incrementtotal count, decrementl and incrementr and continue.
-
In the implementation of this method, create a variable
-
Now, call the helper method created above for both odd length palindromes and even length palindromes,
by supplying left and right indexes as
i, i for odd length palindromes, theni, i+1 for even length palindromes. Then, keep track of total palindromes found, both odd length palindromes and even length palindromes.
For example, when you expand around center for input string "babad", it will produce below output as
If you see the input string, every single character is a palindrome on its own, they are 'b', 'a',
'b', 'a' and 'd', then there are two other odd length palindromes 'bab' and 'aba'
and there are no even length palindromes in the input string.
Complexity Analysis:
Time complexity: Above code runs in O(n2) time where
Space complexity: O(1), since we are keep tracking of total count only.
Above implementations source code can be found at