题目:
给定一个字典,每个字典条目为1个字符串,字符串最少1个字符,最多6个字符。字典中的条目并不是按序的,但每个条目都是唯一的。
输入一个字符串,判断字典中是否有条目可以通过将该字符串调整字符位置得到,如果有多个这样的条目,按字典序输出,如果没有则输出"NOT A VALID WORD"。
解题思路:
1 首先将字典按字典序排序。
2 对每个输入的字符串,遍历字典查找符合条件的条目,当比较输入字符串和字典条目时,可以先比较长度,如果长度不同,该条目肯定不符合条件,如果长度相同,再对该条目和输入字符串分别排序,如果排序后两个字符串相同,则该条目符合条件,否则不符合条件。找到符合条件的条目时,输出该条目。如果没有找到符合条件的条目,输出"NOT A VALID WORD"
代码:
#include<stdio.h>
#include<string.h>
char dictionary[100][8]; //保存字典
int n; //字典的大小
char *index[100]; //字典的索引
char s[8];
int cmp(const void *a, const void *b)
{
char *p1, *p2;
p1= *(char**)a;
p2= *(char**)b;
return strcmp(p1,p2);
}
int cmp_char(const void *a, const void *b)
{
return *(char*)a - *(char*)b;
}
//对字符串进行插入排序
void insert_sort(char *s)
{
int i=1,j;
char ch;
while(s[i] != '\0')
{
ch = s[i];
j=i-1;
while(j>=0 && s[j]>ch) {s[j+1]=s[j];j--;}
s[j+1] = ch;
i++;
}
}
/*判断两个字符串是否由相同的字母构成,
即一个字符串可由另一个字符串调整字符位置得到 */
int is_equal(char *a, char *b)
{
char s1[8], s2[8];
int i;
if(strlen(a) != strlen(b)) return 0;
//复制
i=0;
while(a[i] != '\0') {s1[i]=a[i]; s2[i]=b[i]; i++;};
s1[i]='\0';
s2[i]='\0';
//对两个字符串排序,用插入排序程序运行时间16MS,用快排时间0MS
//insert_sort(s1);
//insert_sort(s2);
qsort(s1, strlen(s1), 1, cmp_char);
qsort(s2, strlen(s2), 1, cmp_char);
//比较是否相等
i=0;
while(s1[i] != '\0')
{
if(s1[i] != s2[i]) return 0;
i++;
}
return 1;
}
int main()
{
int i,flag;
//输入字典
n=0;
scanf("%s", dictionary[n]);
while(dictionary[n][0] != 'X')
{
index[n] = dictionary[n];
n++;
scanf("%s", dictionary[n]);
}
//对字典索引排序
qsort(index, n, sizeof(char*), cmp);
//输入待猜字符串并输出结果
scanf("%s", s);
while(s[0] != 'X')
{
flag=0;
for(i=0; i<n; i++)
if(is_equal(s, index[i])) {printf("%s\n", index[i]); flag=1;}
if(!flag) printf("NOT A VALID WORD\n");
printf("******\n");
scanf("%s", s);
}
return 0;
}