温馨提示×

理解并实现C语言中的回文分割算法

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

回文分割算法是将给定的字符串分割成若干个回文子串的算法。回文串是指正着读和倒着读都一样的字符串。下面是一个简单的C语言实现回文分割算法的示例:

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

// 判断字符串是否为回文串
int isPalindrome(char *str, int start, int end) {
    while (start < end) {
        if (str[start] != str[end]) {
            return 0;
        }
        start++;
        end--;
    }
    return 1;
}

// 回文分割函数
void palindromePartition(char *str, int start, int len, char *output, int k) {
    if (start >= len) {
        output[k] = '\0';
        printf("%s\n", output);
        return;
    }
    
    for (int i = start; i < len; i++) {
        if (isPalindrome(str, start, i)) {
            int length = i - start + 1;
            strncpy(output + k, str + start, length);
            output[k + length] = ' ';
            palindromePartition(str, i + 1, len, output, k + length + 1);
        }
    }
}

int main() {
    char str[] = "aab";
    int len = strlen(str);
    char output[100];
    palindromePartition(str, 0, len, output, 0);
    return 0;
}

在这个示例中,isPalindrome()函数用于判断一个字符串是否为回文串,palindromePartition()函数用于递归地进行回文分割。在main()函数中,我们定义了一个输入字符串str,并调用palindromePartition()函数进行回文分割。

运行这段代码,输出如下:

a a b
aa b

0