Palindromic Substrings
Given a string s
Note: A string is palindromic if it reads the same forward and backward. For example abcba is a palindromic string that expands from center letter c and abba is also a palindromic string that expands with no center letter.
Example 1
Output: 3
Explanation: there are three palindromic substrings in the input string "a", "b" and "c".
Example 2
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
that takes parameters input stringexpandAroundCenterHelper , ints and intl left and right indexes to expand around and count number of palindromes found from that index.r-
In the implementation of this method, create a variable
to keep track of all palindromes found.total -
We will then try to expand the palindromic substring using left and right indexes
andl .r -
While
andl within the boundararies of input string's length, check character atr th index andl th indexes are same, that means we have found a palindrome, then incrementr count, decrementtotal and incrementl and continue.r
-
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
for odd length palindromes, theni, i for even length palindromes. Then, keep track of total palindromes found, both odd length palindromes and even length palindromes.i, i+1
l= i;
r= i;
l= i;
r= i+1;
For example, when you expand around center for input string "babad", it will produce below output as 7
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.
public class PalindromicSubstrings {
static int expandAroundCenter(String s) {
int total = 0;
for (int i=0; i<s.length(); i++) {
int oddLengthPalindromes = expandAroundCenterHelper(s, i, i);
int evenLengthPalindromes = expandAroundCenterHelper(s, i, i+1);
total += oddLengthPalindromes + evenLengthPalindromes;
}
return total;
}
static int expandAroundCenterHelper(String s, int l, int r) {
int total = 0;
while(l>=0 && r<s.length() && s.charAt(l) == s.charAt(r)) {
total++;
l--;
r++;
}
return total;
}
}
Complexity Analysis:
Time complexity: Above code runs in O(n2) time where n
Space complexity: O(1), since we are keep tracking of total count only.
Above implementations source code can be found at