Skip to main content
2 of 2
added 2 characters in body; edited tags; edited title; added 95 characters in body
200_success
  • 145.6k
  • 22
  • 191
  • 481

Count palindrome substrings

Given a string S, count and return the number of substrings of S that are palindromes. Single length substrings are also palindromes. We just have to count the substring that are palindrome.

INPUT: aba
OUTPUT: 4
EXPLANATION: String aba has a,b,a,aba as palindromic substrings.

My code is running correctly but I need more efficient code.

public class PalindromeSubstrings {

    public static int countPalindromeSubstrings(String s)
    {
        String a;
        int countSubs=s.length();
        for(int i=0;i<s.length();i++)
        {
          for(int j=i+2;j<=s.length();j++)
          {
            a=s.substring(i,j);
            countSubs+=count(a);
          }
        }
        return countSubs;
    }
    public static int count(String a)
    {
        for(int i=0;i<a.length();i++)
        {
            if(a.charAt(i)!=a.charAt(a.length()-1-i))
                return 0;
        }
        return 1;
    }
}
sahil mehta
  • 61
  • 1
  • 2
  • 5