Palindromic Substrings
Count the palindromes inside a string by growing outward from each letter and from each gap between two letters.
Given a string s"bc""abc"
Example 1
Output: 3
Explanation: "a", "b", "c".
Example 2
Output: 6
Explanation: "a" three times, "aa" twice, and "aaa".
The Idea
Words such as "noon" and "level" read the same in both directions. Here we hunt for such runs of letters inside one string. In Example 1, "abc""ab""bc""abc"
Example 2, "aaa""a""aa""aa""aaa""aa"
Look at a palindrome from the middle out. "abba""bb""bb"a
The center can be a letter, like the c"abcba""abba""abba"
Each row starts at one center and grows outward while the two end letters match. In the row labelled "on letter 1", the bab"bb"a"abba"
Why is the stop safe? Any wider substring around the bab
Solution Approach
Three questions shape the code: why not check every substring, how to visit every center, and how far to grow from each one. A table that records which substrings are palindromes reaches the same count in another way.
Checking every substring
Why not simply test every substring? Two loops pick a start and an end, which gives n(n + 1) / 2 substrings, 10 for "abba""abba"b"bb"
Visiting every center
How do we reach both kinds of center in one loop? A variable centersleftrightcenterleftcenterrightcenter + 1right
Growing from one center
How far does one center grow? While leftrightleftrightleftright
A table of palindromes
What if we stored the answers instead? Let dp[i][j]"abba"dp[0][3]adp[1][2]"bb"
If the table is filled so that each inside is ready before its outside, every entry costs one comparison and one lookup. Reusing the stored answer for "bb""abba""abba"
Java Solution
The method countSubstrings
- First, set
to 0. A loop movescount over every position ofcenter , from 0 to the last.s - For each
, callcenter to grow from the letter, thenexpand(s, center, center) to grow from the gap after it, and add both results toexpand(s, center, center + 1) .count - Inside
, the parametersexpand andleft are the two ends, and a counterright starts at 0. Afound loop runs as long aswhile andleft are inside the string andright equalss.charAt(left) . Each pass adds one tos.charAt(right) , then movesfound down by one andleft up by one.right returnsexpand . Once the loop overfound ends,center returnscountSubstrings .count
The main"abba""abcba"
public class PalindromicSubstrings {
public static int countSubstrings(String s) {
int count = 0;
for (int center = 0; center < s.length(); center++) {
count += expand(s, center, center); // odd lengths: center on a letter
count += expand(s, center, center + 1); // even lengths: center between letters
}
return count;
}
// Each step outward whose two ends match is one more palindrome.
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 = {"abc", "aaa", "abba", "abcba", "a", ""};
for (String s : inputs) {
System.out.println("\"" + s + "\" -> " + countSubstrings(s));
}
}
}
Running it prints:
"abc" -> 3
"aaa" -> 6
"abba" -> 6
"abcba" -> 7
"a" -> 1
"" -> 0
"abc" -> 3"aaa" -> 6"abba" -> 6"bb""abba"
In "abcba" -> 7"bcb""abcba"ccenter
The gap call is easy to leave out, and nothing breaks loudly when it is missing. A version that grows only from letters returns 4 for "aaa""aa""abba""bb""abba"
The original implementation,
Complexity
The work is the two calls to expand
- Time: O(n²), because each of the 2n calls to
moves outward at most about n / 2 times, and a string of one repeated letter, likeexpand , makes the calls near the middle go that far."aaa" - Space: O(1), because the method keeps only
,count and the two endscenter andleft , with no table of which substrings are palindromes.right
Growing from centers also finds the longest palindrome in a string, instead of counting them all: see