Palindrome Count

Given a string S, count the number of non-empty substrings that are palindromes.
A sub-string is any continuous sequence of characters in the string.
A string is said to be palindrome if the reverse of the string is the same as itself.
Two substrings are different if they occur at different positions in S

Example:

Input:  s = "dskjkd"
Output: 7

Approach

C++

#include <bits/stdc++.h>
using namespace std;

long palindromeString(string s)
{
    long imcenterr;
    long n = s.size();
    string tmp = "";

    //create a temp string
    //with adding special character
    // $ between two adjacent characters
    //of the string
    for (i = 0i < ni++)
    {
        tmp += '$';
        tmp += s[i];
    }
    tmp += '$';
    m = tmp.size();
    long a[m];
    r = -1;
    center = 0;
    for (i = 0i < mi++)
    {
        if (i > r)
        {
            center = i;
            r = i;
            while ((r < m) && (2 * center - r >= 0) &&
                   (tmp[r] == tmp[2 * center - r]))
                r++;
            a[i] = (r - center);
            r--;
        }
        else
        {
            long k = a[2 * center - i];
            if (k <= (r - i + 1))
            {
                a[i] = k;
                if (k == (r - i + 1))
                {
                    center = i;
                    while (r < m && (2 * center - r >= 0) &&
                           (tmp[r] == tmp[2 * center - r]))
                        r++;
                    a[i] = r - center;
                    r--;
                }
            }
            else
            {
                a[i] = (r - i + 1);
            }
        }
    }
    long cnt = 0;
    for (i = 0i < mi++)
        cnt += a[i] / 2;
    return cnt;
}
int main()
{
    string s = "dskjkd";

    cout << palindromeString(s<< "\n";

    return 0;
}


No comments:

Post a Comment