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

   2024-10-20 4480
核心提示:#include stdio.h#include string.hint checkPalindrome(char *str, int start, int end) {if (start = end) {return 1;}if (str

#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函数进行检测。根据函数的返回值,输出相应的结果。

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

 
举报打赏
 
更多>同类网点查询
推荐图文
推荐网点查询
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号