点击打开链接
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <cstring>
#include <string.h>
#include <algorithm>
#include <vector>
#include <numeric>
#include <limits>
#include <math.h>
#include <queue>
#include <map>
#include <set>
#include <stack>
using namespace std;
//每个节点有26个分之。
class Trie {
public:
const int R=26;
struct Node{
bool is_word = false;
Node *next = NULL;
};
Node root;
/** Initialize your data structure here. */
Trie() {
}
/** Inserts a word into the trie. */
void insert(string word) {
if(word.empty()) return;
Node* x= &root;
int p =0;
while (p<word.size()) {
if(!(x->next)) x->next = new Node[R]; //申请了26个R
x = & x->next[word[p++]-'a'];
}
x->is_word = true;
}
/** Returns if the word is in the trie. */
bool search(string word) {
Node x = root;
int p = 0;
while(x.next && p<word.size()){
x = x.next[word[p++]- 'a'];
}
return p== word.size() && x.is_word;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
Node x = root;
int p =0;
while (x.next && p<prefix.size()) {
x = x.next[prefix[p++]-'a'];
}
return p==prefix.size() && (x.is_word || x.next);
}
};
int main()
{
Trie temple;
return 0;
}