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

Edge cases to test

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 count

C++

#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