Java String Program · S59
Count Palindromic Substrings in Java
Count every palindromic substring, where the same text at two different positions counts twice. Each centre contributes one palindrome for every step it can expand.
Problem Statement
Given a string, return how many of its substrings are palindromes. Substrings at different positions are counted separately, even if their text is the same.
Every single character is a palindrome, so a string of length n has at least n palindromic substrings.
Input/Output Examples
"aba"Output4Explanation: a, b, a and aba."abba"Output6Explanation: a, b, b, a, bb and abba."abc"Output3Explanation: only the single characters.Visual Explanation
- Odd centresfoundabbaeach character +4
- Gap b|bfoundbbb = b +1
- Expandfoundabbaa = a +1
- Doneother gaps fail at once6
"abba": every character is a palindrome of length 1, the gap between the two b's starts "bb", and expanding once more gives "abba".Each successful expansion step around a centre is exactly one new palindrome, so the count is simply the total number of successful steps over all 2n - 1 centres.
Approaches
Both approaches look at every possible palindrome. Expanding around centres needs no table; the DP version marks every palindromic substring.
Approach 1: Expand Around Center (Recommended)
Idea: for each centre, expand while the characters match and count each successful step.
- Use every index as an odd centre and every gap as an even centre.
- Expand outwards while
s[left] == s[right]. - Add the number of successful expansions to the total.
Time: O(n²) · Space: O(1).
Approach 2: DP Table
Idea: pal[i][j] is true when the ends match and the inside is a palindrome; count the true cells.
- Fill the table with
ifrom the end to the start andjfromiupwards. - Set
pal[i][j] = s[i] == s[j] && (j - i < 2 || pal[i + 1][j - 1]). - Count every true cell.
Time: O(n²) · Space: O(n²).
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.
Approach 1: Expand Around Center (Recommended)
The same expansion as in the longest palindromic substring problem, but counting instead of keeping the maximum.
public class PalCountExpand {
// Each successful expansion step around a centre is one more palindrome
static int countPalindromes(String s) {
int count = 0;
for (int c = 0; c < s.length(); c++) {
count += expand(s, c, c); // odd lengths
count += expand(s, c, c + 1); // even lengths
}
return count;
}
private static int expand(String s, int left, int right) {
int found = 0;
while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
found++;
left--;
right++;
}
return found;
}
public static void main(String[] args) {
String[] inputs = {"aba", "abba", "abc"};
for (String s : inputs) {
System.out.println("\"" + s + "\" -> " + countPalindromes(s));
}
}
}
"aba" -> 4 "abba" -> 6 "abc" -> 3
Time complexity: O(n²) · Space complexity: O(1).
Approach 2: DP Table
Uses more memory, but the table can answer "is this substring a palindrome?" for any pair afterwards.
public class PalCountDp {
// pal[i][j] = s[i..j] is a palindrome; count every true cell
static int countPalindromes(String s) {
int n = s.length();
boolean[][] pal = new boolean[n][n];
int count = 0;
for (int i = n - 1; i >= 0; i--) {
for (int j = i; j < n; j++) {
pal[i][j] = s.charAt(i) == s.charAt(j) && (j - i < 2 || pal[i + 1][j - 1]);
if (pal[i][j]) {
count++;
}
}
}
return count;
}
public static void main(String[] args) {
String[] inputs = {"aba", "abba", "abc"};
for (String s : inputs) {
System.out.println("\"" + s + "\" -> " + countPalindromes(s));
}
}
}
"aba" -> 4 "abba" -> 6 "abc" -> 3
Time complexity: O(n²) · Space complexity: O(n²).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Expand Around Center | O(n²) | O(1) |
| DP Table | O(n²) | O(n²) |
Here n is the length of the string. A string like "aaaa" has n(n + 1) / 2 palindromic substrings, so counting them one by one is inherently quadratic in the worst case.
Interview Tips and Recommended Approach
- Count positions, not distinct texts.
"aaa"has 6 palindromic substrings, though only 3 distinct ones. - Include even centres. Missing them loses every even-length palindrome.
- Reuse the expansion helper. Returning the number of steps makes counting a one-line change.
- Mention Manacher's algorithm for an
O(n)solution if the interviewer asks for better.
Recommended Approach: Expand Around Center
Why: it counts every palindrome exactly once with constant extra memory, and it shares its core with the longest palindromic substring solution.