1

Given a string S, I want to count the number of distinct palindromic substrings of S. I know the basic O(n^2) approach to do so. But I want to find a better approach for strings that can be very large (of the order of 10^5).

So I want a more efficient algorithm.

Example:

Say S=xyx, then the palindromic counter must return 3 as answer, as S has three palindromic substrings: {x,xyx,y}.

My code :

int countPalindrome(char *str)
{
int i,j,k,count=0;
for(i=0;str[i];i++)
{
    k=i-1;j=i+1;  //count odd length palindromes
    while(k>=0 && str[j] && str[k]==str[j])
    {
        ++count;
        k--;j++;
    }

    k=i;j=i+1; //count even length palindrome
    while(k>=0 && str[j] && str[k]==str[j])
    {
        ++count;
        k--;j++;
    }
}
return count;
}

Clearly its O(n^2) and even does not provide distinct but all palindromes .Can someone provide a better algorithm to count Distinct Palindromic Substrings

user3086701
  • 63
  • 1
  • 5

0 Answers0