POJ 2001 Shortest Prefixes ( 字典树 )

题意:给出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 ;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值