查找判断的时候千万不要加if(strcmp(ch1, ch2) != 0),只因这一句,多WA了两次
Hat’s Words
You are to find all the hat’s words in a dictionary.
Only one case.
Your output should contain all the hat’s words, one per line, in alphabetical order.
ahat
hatword
下面是代码 31Ms
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define max 26
typedef struct t_node //字典树结点
{
struct t_node * child[max];
char ch; //标记是否是单词的结尾
}t_node, * Node;
Node root;
char st[50000][100]; //保存输入的字符串
void insert(char * str) //将字符串str放入字典中
{
int i, index, len;
Node current, newnode;
len = strlen(str);
if(len == 0)
return ;
current = root;
for(i = 0; i < len; i ++)
{
index = str[i] - 'a'; //寻找该存放的位置
if(current->child[index] != NULL) //如果存在,继续往下找
{
current = current->child[index];
}
else //如果没有该结点,新增一个结点
{
newnode = (Node) calloc (1, sizeof(t_node));
current->child[index] = newnode;
current = newnode;
}
}
current->ch = 1; //标记是否为单词的结尾,1为是
}
int find(char * str) //查找字符串str是否在字典树中
{
int i, index, len;
Node current;
char ss[100];
len = strlen(str);
if(len == 0)
return 0;
current = root;
for(i = 0; i < len; i ++)
{
index = str[i] - 'a';
if(current->child[index] != NULL) //如果存在,继续
{
current = current->child[index];
}
else //如果没有,返回0
return 0;
}
if(current->ch == 1) //如果是一个完整的单词,返回1
return 1;
return 0;
}
int main()
{
int j, k, i = 0;
char s[100], ch1[100], ch2[100];
root = (Node) calloc (1, sizeof(t_node));
while(scanf("%s", s) != EOF)
{
strcpy(st[i ++], s);
insert(s);
}
for(j = 0; j < i; j ++)
{
for(k = 0; k < strlen(st[j]); k ++) //判断前后两个子串是否都是字典中的单词
{
strcpy(ch2, st[j] + k + 1);
strcpy(ch1, st[j]);
ch1[k+1] = '\0';
if(find(ch1) && find(ch2))
{
puts(st[j]);
break;
}
}
}
return 0;
}