AI写作智能体 自主规划任务,支持联网查询和网页读取,多模态高效创作各类分析报告、商业计划、营销方案、教学内容等。 广告
#### [208\. 实现 Trie (前缀树)](https://leetcode-cn.com/problems/implement-trie-prefix-tree/) ```cpp class Trie { public: const static int kCharSize = 26; struct Node { bool isWorld; char ch; Node* child[kCharSize]; Node(char c) : isWorld(false), ch(c) { for (int i = 0; i < kCharSize; i++) { child[i] = nullptr; } } }; /** Initialize your data structure here. */ Trie() { root = new Node(0); } ~Trie() { delNode(root); } void delNode(Node* node) { for (int i = 0; i < kCharSize; i++) { if (node->child[i] != nullptr) { delNode(node->child[i]); } } delete node; } /** Inserts a word into the trie. */ void insert(string word) { Node* node = root; for (auto c : word) { int index = c - 'a'; if (node->child[index] == nullptr) { node->child[index] = new Node(c); } node = node->child[index]; } node->isWorld = true; } /** Returns if the word is in the trie. */ bool search(string word) { Node* node = root; for (auto c : word) { int index = c - 'a'; if (node->child[index] == nullptr) return false; node = node->child[index]; } return node->isWorld; } /** Returns if there is any word in the trie that starts with the given prefix. */ bool startsWith(string prefix) { Node* node = root; for (auto c : prefix) { int index = c - 'a'; if (node->child[index] == nullptr) return false; node = node->child[index]; } return true; } private: Node* root; }; ```