UVA-156 Ananagrams
题目大意: 输入一些单词,按字典序顺序输出无视大小写及字母排列顺序后,只出现一次的单词。如 STOP、SOPT、spTO 算重复出现。
Sample Input
ladder came tape soon leader acme RIDE lone Dreis peat
ScAlE orb eye Rides dealer NotE derail LaCeS drIed
noel dire Disk mace Rob dries
#
Sample Output
Disk
NotE
derail
drIed
eye
ladder
soon
解题思路: 先将输入的单词转为小写同时存在另一个临时数组中,再将单词按照字母序排列,两两比较如果相等则标记一下,将没有标记过的存给另一个结果数组中,按字母表排序,依次输出
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
using namespace std;
char word[100][50];
char temp[100][50];
char ans[100][50];
int num[100] = {0};
int cmp1(const void*a,const void*b) {
return *(char*)a - *(char*)b;
}
int cmp2(const void*a, const void*b) {
return strcmp((char*)a, (char*)b);
}
int main() {
int i = 0;
while (scanf("%s",word[i]) && strcmp(word[i],"#")) {
for (int j = 0; j < strlen(word[i]); j++) {
if (word[i][j] >= 'A' && word[i][j] <= 'Z')
temp[i][j] = word[i][j] + 'a' - 'A';
else
temp[i][j] = word[i][j];
}
qsort(temp[i],strlen(temp[i]),sizeof(temp[i][0]),cmp1);
//要比较的数组,比较的数组的多少个元素,比较的第一个元素的长度,比较规则
i++;
}
for (int j = 0; j < i; j++) {
for (int k = j + 1; k < i; k++) {
if (strcmp(temp[j],temp[k]) == 0) {
num[j]++;
num[k]++;
}
}
}
int h = 0;
for (int j = 0; j < i; j++) {
//之前外面写的是int h; 里面写的是int j = 0, h = 0;
// 此处h又重新定义了,for 循环结束后,h 释放 后面还要用到 h ,所以已知出不来
if(num[j] == 0)
strcpy(ans[h++],word[j]);
}
qsort(ans, h, sizeof(ans[0]), cmp2);
//之前一直写错是因为把这里的 sizeof 写成了 strlen 。。。。然后总是得到一堆奇奇怪怪的数据
for (int j = 0; j < h; j++) {
cout << ans[j] << endl;
}
return 0;
}