Data Structures & Algorithms in Java – Strings – Palindromic substrings


Given a string , find the number of palindromic substrings in the string.

For example , for the input “babad” the number of palindromic substrings is 7:

“b” , “a”, “b”,”a”,”d” , “aba” , “bab”

Try out the solution here:



The solution is almost the same as we discussed in the previous post:

The only difference is instead of finding the length of the maximum window and its start position we increment a count variable each time we find a palindrome.

Here is the modified code:

class Solution {
    int no = 0;
    public int countSubstrings(String s) {
        if(s.length() == 1) return 1;
        char[] array = s.toCharArray();
        for(int i=0;i<s.length();i++){
        return no;
        void check(char[] a,int i,int j){
            while(i>=0 && j < a.length && a[i] == a[j]){

As you see everytime a palindrome is found out the count is incremented.

That’s it!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s