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: Stringabahasa,b,a,abaas 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;
}
}