您的位置:首页 > 其它

UVA 156 - Ananagrams

2013-01-23 15:29 288 查看
首先进行单词的大写转小写,然后重排,所以得保存两份单词进行操作。当然,还要标记这个单词重排后是否出现两次,所以还需要一个flag作为标记。处理完成后,最后还需要按照原先单词的字典顺序输出,所以还需要排一次序。

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

struct _s {
    char a[25];
    char b[25];
    bool flag;
}s[10000];

void trans(char st[]) {
    int len = strlen(st);
    // 大写转小写
    for (int i=0; i<len; i++)
        if (st[i]>='A' && st[i]<='Z')
            st[i] += ('a'-'A');
    // 冒泡排序
    for (int i=len; i>0; i--)
        for (int j=0; j<i; j++) {
            if (st[j] < st[j-1]) {
                char tmp = st[j];
                st[j] = st[j-1];
                st[j-1] = tmp;
            }
        }
}
// 根据b排序
int cmp_b(const void *_a, const void *_b) {
    struct _s *a = (struct _s*)_a;
    struct _s *b = (struct _s*)_b;
    return strcmp(a->b, b->b);
}
// 根据a排序
int cmp_a(const void *_a, const void *_b) {
    struct _s *a = (struct _s*)_a;
    struct _s *b = (struct _s*)_b;
    return strcmp(a->a, b->a);
}

int main() {
    char st[25];
    int n = 0;

    while (scanf("%s", st)) {
        if ('#' == st[0])
            break;
        strcpy(s
.a, st);
        trans(st);
        strcpy(s
.b, st);
        n++;
    }

    qsort(s, n, sizeof (s[0]), cmp_b);

    for (int i=1; i<n; i++)
        if (0 == strcmp(s[i].b, s[i-1].b)) {
            s[i].flag = 1;
            s[i-1].flag = 1;
        }

    qsort(s, n, sizeof (s[0]), cmp_a);

    for (int i=0; i<n; i++) {
        if (!s[i].flag)
            printf("%s\n", s[i].a);
    }
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: