在C語(yǔ)言中實(shí)現(xiàn)對(duì)回文編碼的解碼和驗(yàn)證

小樊
83
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;
}

這個(gè)程序首先定義了兩個(gè)函數(shù),一個(gè)用于檢查一個(gè)字符串是否為回文,另一個(gè)用于解碼回文編碼的字符串。主函數(shù)中定義了一個(gè)回文編碼字符串,并調(diào)用解碼函數(shù)對(duì)其進(jìn)行解碼,然后調(diào)用回文檢查函數(shù)判斷解碼后的字符串是否為回文。

0