Uva 1339:Ancient Cipher

題目傳送門:Uva 1339:Ancient Cipher

題目大意:第二個字符串的每個字母和另一個字母一一映射之後,再重新排列能否得到地一個字符串。

思路:一一映射和重排只是改變了字母的值和位置,但是沒有改變字母種類的數量,所以只需統計兩個字符串中每種字母出現的次數,然後對出現次數進行排序,然後比較排序後的兩個數組即可。

例如:
HAHB
MEMC
從ROME到MAMA,字母種類還是隻有三種,每種字母出現的次數分別爲2、1、1(M、E、C)及2、1、1(H、A、B)。所以是什麼字母並不重要。

AC代碼:

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

void swap(int* a, int* b)
{
    int t = *a;
    *a = *b;
    *b = t;
}

int partition(int a[], int p, int q)
{
    int x = a[q];
    int i = p - 1, j;
    for (j = p; j < q; ++j)
        if (a[j] < x)
            swap(&a[++i], &a[j]);
    swap(&a[++i], &a[q]);
    return i;
}

void quickSort(int a[], int p, int q)
{
    if (p < q)
    {
        int m = partition(a, p, q);
        quickSort(a, p, m - 1);
        quickSort(a, m + 1, q);
    }
}

int main()
{
    char a[105], b[105];
    int countA[26], countB[26];
    while (2 == scanf("%s%s", a, b))
    {
        memset(countA, 0, sizeof(countA));
        memset(countB, 0, sizeof(countB));
        int len = strlen(a), i;
        for (i = 0; i < len; ++i)
        {
            countA[a[i] - 'A']++;
            countB[b[i] - 'A']++;
        }
        quickSort(countA, 0, 25);
        quickSort(countB, 0, 25);
        for (i = 0; i < 26; ++i)
            if (countA[i] != countB[i])
                break;
        if (i == 26)
            printf("YES\n");
        else
            printf("NO\n");
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章