C语言中通过递归解决回文排列的检测

2305
2024/3/29 17:32:54
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

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

int checkPalindrome(char *str, int start, int end) {
    if (start >= end) {
        return 1;
    }
    
    if (str[start] != str[end]) {
        return 0;
    }
    
    return checkPalindrome(str, start + 1, end - 1);
}

int main() {
    char str[100];
    printf("Enter a string: ");
    scanf("%s", str);
    
    if (checkPalindrome(str, 0, strlen(str) - 1)) {
        printf("The string is a palindrome permutation.\n");
    } else {
        printf("The string is not a palindrome permutation.\n");
    }
    
    return 0;
}

这段代码首先定义了一个名为checkPalindrome的函数,该函数用于检测给定字符串是否为回文排列。函数的递归思想是,从字符串的开头和结尾开始比较字符是否相等,逐步向中间靠拢,直到整个字符串被检测完毕。如果在任何时候发现不相等的字符,则返回0,否则返回1。

在main函数中,用户输入一个字符串,然后调用checkPalindrome函数进行检测。根据函数的返回值,输出相应的结果。

可以通过在终端中编译并运行该程序,输入一个字符串,程序将告诉你该字符串是否为回文排列。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: c语言二维数组怎么作为参数传递