How to check whether each substring range (L to R) from an array of substring ranges is a palindrome in C

1 Answer

0 votes
#include <stdio.h>
#include <string.h>
#include <stdbool.h>

#define ROWS 3
#define MAX_LEN 32

bool isPalindrome(const char* str, int left, int right) {
    while (left < right) {
        if (str[left++] != str[right--]) {
            return false;
        }
    }
    
    return true;
}

void checkRangesForPalindrome(const char* str, int rows, const int query[][2]) {
    char substring[MAX_LEN];

    for (int i = 0; i < rows; i++) {
        int start = query[i][0];
        int end = query[i][1];
        int len = end - start + 1;

        strncpy(substring, str + start, len);
        substring[len] = '\0';  // Null-terminate the substring

        printf("%s: %s\n", substring,
               isPalindrome(str, start, end) ? "Palindrome" : "Not palindrome");
    }
}

int main() {
    const char str[] = "abcddcbeebc";
    const int ranges[ROWS][2] = {{2, 5}, {5, 10}, {3, 7}};

    checkRangesForPalindrome(str, ROWS, ranges);

    return 0;
}



/*
run:

cddc: Palindrome
cbeebc: Palindrome
ddcbe: Not palindrome

*/



 



answered 10 hours ago by avibootz

Related questions

...