Trie树

字典树查询

#include<iostream>
#include<cstring>
#include<malloc.h>

using namespace std;

const int maxn = 30;

typedef struct Trie{
	int v;
	Trie *next[ maxn ];
}Trie;

Trie root;

void CreateTrie( char *str ){
	int len = strlen( str );
	//cout << str << endl;
	Trie *p = &root, *q;
	for( int i = 0; i < len; ++i ){
		int id = str[ i ] - 'a';
		if( p -> next[ id ] == NULL ){
			//q = new Trie;
			q = ( Trie * )malloc( sizeof( root ) );
			for( int j = 0; j < maxn; ++j ){
				q -> next[ j ] = NULL;
			}
			q -> v = 1;
			p  -> next[ id ] = q;
		}
		else{
			p -> next[ id ] -> v++;
		}
		p = p -> next[ id ];
	}
}

int FindTrie( char *str ){
	int len = strlen( str );
	Trie *p = &root;
	for( int i = 0; i < len; ++i ){
		int id = str[ i ] - 'a';
		if( p -> next[ id ] == NULL ){
			return 0;
		}
		p = p -> next[ id ];
	}
	return p -> v;
}


int main(){
	int n, m;
	char str[ maxn ];
	for( int i = 0; i < maxn; ++i ){
		root.next[ i ] = NULL;
	}
	cin >> n;
	while( n-- ){
		cin >> str;
		CreateTrie( str );
	}
	memset( str, 0, sizeof( str ) );
	cin >> m;
	while( m-- ){
	cin >> str;
		int ans = FindTrie( str );
		cout << ans << endl;
	}
	return 0;
}

/*
5
banana
band
bee
absolute
acm

4
ba
b
band
abc






2
3
1
0 
*/


原文地址:https://www.cnblogs.com/yfceshi/p/6731663.html