题意:给出n个单词(1<=n<=1000),求出每个单词的非公共前缀,如果没有,则输出自己。
分析:字典树的基础应用。
Trie树(字典树),又称单词查找树或键树,是一种树形结构,是一种哈希树的变种。典型应用是用于统计和排序大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计。它的优点是:最大限度地减少无谓的字符串比较,查询效率比哈希表高。
它有3个基本特性:
1)根节点不包含字符,除根节点外每一个节点都只包含一个字符。
2)从根节点到某一节点,路径上经过的字符连接起来,为该节点对应的字符串。
3)每个节点的所有子节点包含的字符都不相同。
//564K 16MS
#include <cstdio>
#include <iostream>
#include <cstring>
#define DEBUG puts("Hello world!") ;
#define N 30
using namespace std ;
struct TreeNode
{
int count ; // 记录用到这个节点的单词数量,如果count = 1,则证明其为这个单词唯一的节点
TreeNode *next[N] ;
TreeNode( )
{
count = 0 ;
memset ( next , 0 , sizeof ( next ) ) ;
}
};
TreeNode *root ;
void
Insert ( char * str )
{
TreeNode * temp ;
temp = root ;
int i ;
i = 0 ;
//DEBUG
while ( str[i] )
{
int index ;
index = str[i] - 'a' ;
if ( NULL == temp->next[index] )
{
temp->next[index] = new TreeNode ;
}
temp = temp->next[index] ;
temp->count ++ ;
i ++ ;
}
}
void
Search ( char *str )
{
TreeNode *temp ;
temp = root ;
int i ;
i = 0 ;
while ( str[i] )
{
int index ;
index = str[i] - 'a' ;
if ( 1 == temp->count )
{
break ;
}
printf ("%c" , str[i] ) ;
temp = temp->next[index] ;
i ++ ;
}
}
int
main ( )
{
root = new TreeNode ;
char str[1005][22] ;
int index ;
index = 0 ;
while ( EOF != scanf ("%s" , str[index] ) )
{
Insert ( str[index] ) ;
index ++ ;
}
int len ;
len = index ;
for ( int i = 0 ; i < len ; i ++ )
{
printf ("%s " , str[i] ) ;
Search ( str[i] ) ;
printf ("\n") ;
}
return 0 ;
}