问题:给定一个英语词典,找出其中的所有变位词集合。例如,”pots”,”stop”和”tops”互为变位词,因为每一个单词都可以通过改变其他单词中的字母顺序来得到。
标记词典中的每一个词,使得在相同变位词类中的单词具有相同标识符。然后将具有相同标识的单词集中在一起。对于的一个问题,我们使用基于排序的标识:将单词中的字母按照字母表顺序排列。第二个问题,我们将所有的单词按照其标识的顺序排序。
Qsort对字符串中的字符排序
Sort对字符串排序
Squash输出相同变位词的字符串
// 原始数据
char *wordList[20];
// 字符排序后数据
char *signList[20];
// qsort函数排序比较函数
int charcmp(const void *x, const void *y)
{
return *(char *)x-*(char *)y;
}
// 对数组中的字符串按照a,b,c排序
void sort(int num)
{
char *temp1 = NULL, *temp2 = NULL;
for(int i = 0; i < num; i++)
{
for(int j = i + 1; j < num; j++)
{
if(strcmp(signList[j], signList[i]) < 0)
{
temp1 = signList[i];
signList[i] = signList[j];
signList[j] = temp1;
temp2 = wordList[i];
wordList[i] = wordList[j];
wordList[j] = temp2;
}
}
}
temp1 = NULL;
temp2 = NULL;
for(int i = 0; i < num; i++)
{
qDebug("%s, %s", signList[i], wordList[i]);
}
}
// 输出具有相同标记的字符
void squash(int num)
{
char cOld[20], cNew[20];
if(signList[0])
{
strcpy(cOld, signList[0]);
}
int nRepeatCount = 0;
for(int i = 0; i < num; i++)
{
strcpy(cNew, signList[i]);
if(strcmp(cNew, cOld) == 0)
{
qDebug("%s", wordList[i]);
}
else
{
strcpy(cOld, signList[i]);
qDebug("\n");
qDebug("%s", wordList[i]);
}
/*
if(strcmp(cNew, cOld) == 0)
{
nRepeatCount++;
}
else
{
qDebug("%s, %d", signList[i-1], nRepeatCount);
strcpy(cOld, signList[i]);
nRepeatCount = 1;
if(i == num - 1)
{
qDebug("%s, %d", signList[i-1], nRepeatCount);
}
}
*/
}
}
int main(int argc, char **argv)
{
QApplication app(argc, argv);
char sign[20] = "pans";
for(int k = 0; k < 6; k++)
{
signList[k]=(char *)malloc(sizeof(sign));
wordList[k]=(char *)malloc(sizeof(sign));
}
strcpy(wordList[0], sign);
qsort(sign, strlen(sign), sizeof(char), charcmp);
strcpy(signList[0], sign);
char sign1[20] = "pots";
strcpy(wordList[1], "pots");
qsort(sign1, strlen(sign1), sizeof(char), charcmp);
strcpy(signList[1], sign1);
char sign2[20] = "opt";
strcpy(wordList[2], "opt");
qsort(sign2, strlen(sign2), sizeof(char), charcmp);
strcpy(signList[2], sign2);
char sign3[20] = "snap";
strcpy(wordList[3], "snap");
qsort(sign3, strlen(sign3), sizeof(char), charcmp);
strcpy(signList[3], sign3);
char sign4[20] = "stop";
strcpy(wordList[4], "stop");
qsort(sign4, strlen(sign4), sizeof(char), charcmp);
strcpy(signList[4], sign4);
char sign5[20] = "tops";
strcpy(wordList[5], "tops");
qsort(sign5, strlen(sign5), sizeof(char), charcmp);
strcpy(signList[5], sign5);
sort(6);
squash(6);
return app.exec();
}