温馨提示×

在C语言中实现对回文编码的解码和验证

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

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

// Function to check if a string is a palindrome
int isPalindrome(char str[]) {
    int len = strlen(str);
    for (int i = 0; i < len/2; i++) {
        if (str[i] != str[len-i-1]) {
            return 0;
        }
    }
    return 1;
}

// Function to decode a palindrome-encoded string
void decodePalindrome(char str[], char decoded[]) {
    int len = strlen(str);
    int j = 0;
    for (int i = 0; i < len; i += 2) {
        int count = str[i] - '0';
        char ch = str[i+1];
        for (int k = 0; k < count; k++) {
            decoded[j++] = ch;
        }
    }
    decoded[j] = '\0';
}

int main() {
    char encoded[] = "3a2b1c2b3a";
    char decoded[100];

    decodePalindrome(encoded, decoded);

    printf("Decoded string: %s\n", decoded);

    if (isPalindrome(decoded)) {
        printf("Decoded string is a palindrome.\n");
    } else {
        printf("Decoded string is not a palindrome.\n");
    }

    return 0;
}

这个程序首先定义了两个函数,一个用于检查一个字符串是否为回文,另一个用于解码回文编码的字符串。主函数中定义了一个回文编码字符串,并调用解码函数对其进行解码,然后调用回文检查函数判断解码后的字符串是否为回文。

0