温馨提示×

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

小樊
82
2024-04-26 17:32:54
栏目: 编程语言

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

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

0