经典算法之字典树

字典树(TrieTree)

简介

字典树(前缀树)是字符串匹配问题的常用算法之一,是KMP算法的升级版本,KMP解决单一字符串匹配问题效果极佳,但是对于多个字符串匹配的问题,需要使用字典树效果才显著。

代码
#include <bits/stdc++.h>
using namespace std;

const int NUM = 26;
typedef struct TrieNode{
	bool isWord;
	struct TrieNode *next[NUM];
	TrieNode() :isWord(false){
		memset(next,(int)NULL,sizeof(next));
	}
} TrieNode;

class Trie{
private:
	TrieNode *root;
public:
	Trie(){
		root = new TrieNode();
	}
	void Insert(string& word){
		TrieNode *location = root;
		for (int i = 0;i < (int)word.size();++i){
			if (location->next[word[i] - 'a'] == nullptr){
				TrieNode *temp = new TrieNode();
				location->next[word[i] - 'a'] = temp;
			}
			location = location->next[word[i] - 'a'];
		}
		location->isWord = true;
		return ;
	}
	bool Search(string& word){
		TrieNode *location = root;
		for (int i = 0;i < (int)word.size() && location;++i){
			location = location->next[word[i] - 'a'];
		}
		return (location != nullptr && location->isWord);
	}
	bool StartWith(string& prefix){
		TrieNode *location = root;
		for (int i = 0;i < (int)prefix.size();++i){
			location = location->next[prefix[i] - 'a'];
			if (location == nullptr) return false;
		}
		return true;
	}
	void DeleteTrie(TrieNode *root){
		for (int i = 0;i < NUM;++i){
			if (root->next[i] != nullptr) DeleteTrie(root->next[i]);
		}
		delete root;
	}
};

int main(void){
	// vector<string> v{"abc","ab","abdf","cdd"};
	vector<string> v{"","","a",""};
	string word = "";
	Trie tree;
	for (int i = 0;i < (int)v.size();++i){
		tree.Insert(v[i]);
	}
	cout << tree.Search(word) << endl;
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值