编辑代码

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

bool isPalindromeRecursive(char *str, int start, int end) {
    if (start >= end)
        return true;
    else if (str[start] != str[end])
        return false;
    else
        return isPalindromeRecursive(str, start + 1, end - 1);
}

bool isPalindromeIterative(char *str) {
    int start = 0;
    int end = strlen(str) - 1;
    
    while (start < end) {
        if (str[start] != str[end])
            return false;
        start++;
        end--;
    }
    
    return true;
}

int main() {
    char str[] = "level";
    
    // 递归判断回文字符串
    bool isPalindromeRec = isPalindromeRecursive(str, 0, strlen(str) - 1);
    printf("%s is%s a palindrome (recursive)\n", str, isPalindromeRec ? "" : " not");
    
    // 迭代判断回文字符串
    bool isPalindromeItr = isPalindromeIterative(str);
    printf("%s is%s a palindrome (iterative)\n", str, isPalindromeItr ? "" : " not");
    
    return 0;
}