字典树-学习笔记
程序员文章站
2022-06-04 12:46:28
...
字典树-学习笔记
参考文章
笔记
代码
#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;
}
下一篇: MAC安装并配置Maven环境