Algo-Sim › Dynamic Programming
Palindromic Substrings
Medium · Dynamic Programming · step through it in Java, Python and C++ on your own input
Count every palindromic substring by expanding outward from each of the 2n − 1 centres.
Problem
Given a string s, return how many of its substrings are palindromes. A substring is a contiguous, non-empty run of characters; substrings at different positions count separately even when they contain the same letters.
Constraints
- 1 ≤ s.length ≤ 1000
- s contains only lowercase English letters
- O(n²) time is expected; O(n³) is too slow
Edge cases to test
- One character:
1 - All the same letter: n(n + 1)/2
- Even centres
Follow-up questions
- Why 2n − 1 centres?
- Each letter is an odd centre and each gap between letters an even one.
- Can it be linear?
- Manacher gives every centre’s radius in O(n); the count is the sum of the radii.
Solution
Java
public int countSubstrings(String s) {
int count = 0;
for (int i = 0; i < s.length(); i++) {
count += expand(s, i, i);
count += expand(s, i, i + 1);
}
return count;
}
private int expand(String s, int l, int r) {
int found = 0;
while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) {
found++;
l--;
r++;
}
return found;
}Python
def count_substrings(s):
def expand(l, r):
found = 0
while l >= 0 and r < len(s) and s[l] == s[r]:
found += 1
l, r = l - 1, r + 1
return found
count = 0
for i in range(len(s)):
count += expand(i, i)
count += expand(i, i + 1)
return countC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int countSubstrings(string &s) {
int count = 0;
for (int i = 0; i < int(s.size()); i++) {
count += expand(s, i, i);
count += expand(s, i, i + 1);
}
return count;
}
int expand(string &s, int l, int r) {
int found = 0;
while (l >= 0 && r < int(s.size()) && s[l] == s[r]) {
found++;
l--;
r++;
}
return found;
}
};
More Dynamic Programming problems
- Climbing Stairs: Recursion → Memo → Table (Easy)
- Min Cost Climbing Stairs (Easy)
- House Robber (Medium)
- House Robber II (Medium)
- Coin Change (Medium)
- Coin Change II (Medium)
- Perfect Squares (Medium)
- Combination Sum IV (Medium)
- Decode Ways (Medium)
- Maximum Product Subarray (Medium)
- Best Time to Buy and Sell Stock with Cooldown (Medium)
- Best Time to Buy and Sell Stock with Transaction Fee (Medium)
- Best Time to Buy and Sell Stock III (Hard)
- Longest Increasing Subsequence (Medium)
- Word Break (Medium)
- Unique Paths (Medium)
- Unique Paths II (Medium)
- Minimum Path Sum (Medium)
- Maximal Square (Medium)
- Partition Equal Subset Sum (Medium)
- Target Sum (Medium)
- Longest Common Subsequence (Medium)
- Interleaving String (Medium)
- 0/1 Knapsack (Medium)
- Edit Distance (Medium)
- Distinct Subsequences (Hard)
- Longest Palindromic Substring (Medium)
- Longest Palindromic Subsequence (Medium)
- Predict the Winner (Medium)
- Stone Game (Medium)