溫馨提示×

在C語言中實現對回文編碼的解碼和驗證

小樊
84
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
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女