What it teaches: Counting palindromes: expand from 2n − 1 centres, or a boolean interval table.
Practise it on judges as “Palindromic Substrings”.
The problem
Return the number of palindromic substrings (counted by position) in s.
Example 1
Input: s = "aaa"
Output: 6
Constraints
1 ≤ n ≤ 1000
Pattern clues in the wording
→ Count contiguous palindromes
These clues point to Expand Around Center: Treat every index (and every gap between two indexes) as the middle of a palindrome and grow outwards while both sides match.
Stuck? Take one hint at a time
Solution.java · starter
class Solution {
public int countSubstrings(String s) {
return 0;
}
}
Write your solution locally or in your editor for now. The in-browser runner (Java first, then Python, C++ and more) will run these tests right here.
For each of the 2n − 1 centres, expand while the ends match, counting each step.
Approach 1
class Solution {
public int countSubstrings(String s) {
int count = 0;
for (int c = 0; c < 2 * s.length() - 1; c++) {
int l = c / 2, r = l + c % 2;
while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { count++; l--; r++; }
}
return count;
}
}
class Solution {
public int countSubstrings(String s) {
int n = s.length(), count = 0;
boolean[][] pal = new boolean[n][n];
for (int i = n - 1; i >= 0; i--)
for (int j = i; j < n; j++)
if (s.charAt(i) == s.charAt(j) && (j - i < 2 || pal[i + 1][j - 1])) { pal[i][j] = true; count++; }
return count;
}
}
Verdict: Gives a reusable table (useful for palindrome partitioning).