字典树-学习笔记

字典树-学习笔记

参考文章

浅谈Trie树(字典树)

笔记

在这里插入图片描述

代码

#include <iostream>
#include <algorithm>
#include <string>
#include <cstring>

#define maxn 100005

using namespace std;

int root;
int  trie[27][27];
int tot;

void init() {
	memset(trie, 0, sizeof(trie));
	tot = 0;
}

void insert(const string &s) {
	root = 0;
	for (int i = 0, n = s.size(); i < n; ++i) {
		int j = s[i] - 'a';
		if (!trie[root][j]) trie[root][j] = ++tot;
		root = trie[root][j];
	}
}

bool search(const string &s) {
	root = 0;
	for (int i = 0, n = s.size(); i < n; ++i) {
		int j = s[i] - 'a';
		if (!trie[root][j]) return 0;
		root = trie[root][j];
	}
	return 1;
}

int main() {
	init();
	insert("Hello");
	insert("world");
	cout << search("Hell") << "\n";
	cout << search("world") << "\n";
	return 0;
}
发布了163 篇原创文章 · 获赞 54 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weixin_42856843/article/details/103632621