Untitled

mail@pastecode.io avatar
unknown
c_cpp
7 months ago
1.3 kB
3
Indexable
Never
#include<stdio.h>
#include<string.h>

// Read only region start
char* Sbstring(char* input1)
{
    // Read only region end

    int start = 0; // Starting index of longest palindrome found
    int maxLength = 1; // Maximum length of palindrome found

    int len = strlen(input1);

    int low, high;

    // Check for palindrome of odd length centered at each character
    for (int i = 1; i < len; i++) {
        low = i - 1;
        high = i;
        while (low >= 0 && high < len && input1[low] == input1[high]) {
            if (high - low + 1 > maxLength) {
                start = low;
                maxLength = high - low + 1;
            }
            --low;
            ++high;
        }

        low = i - 1;
        high = i + 1;
        while (low >= 0 && high < len && input1[low] == input1[high]) {
            if (high - low + 1 > maxLength) {
                start = low;
                maxLength = high - low + 1;
            }
            --low;
            ++high;
        }
    }

    char* result = new char[maxLength + 1];
    strncpy(result, &input1[start], maxLength);
    result[maxLength] = '\0';

    return result;
}

int main() {
    char str[] = "cdcdf";
    printf("Longest palindrome is: %s\n", Sbstring(str));
    delete[] Sbstring(str);
    return 0;
}