kali2026.2 2026kali换中文输入法
2026/7/14 4:16:07
Trie(发音类似"try")或者说 前缀树 是一种树形数据结构,用于高效地存储和检索字符串数据集中的键。这一数据结构有相当多的应用情景,例如自动补完和拼写检查。 请你实现 Trie 类:Trie()初始化前缀树对象。voidinsert(String word)向前缀树中插入字符串 word 。 booleansearch(String word)如果字符串 word 在前缀树中,返回true(即,在检索之前已经插入);否则,返回false。 booleanstartsWith(String prefix)如果之前已经插入的字符串 word 的前缀之一为 prefix ,返回true;否则,返回false。 示例: 输入 inputs=["Trie","insert","search","search","startsWith","insert","search"]inputs=[[],["apple"],["apple"],["app"],["app"],["app"],["app"]]输出[null,null,true,false,true,null,true]解释 Trie trie=newTrie();trie.insert("apple");trie.search("apple");// 返回 Truetrie.search("app");// 返回 Falsetrie.startsWith("app");// 返回 Truetrie.insert("app");trie.search("app");// 返回 True提示:1<=word.length,prefix.length<=2000word 和 prefix 仅由小写英文字母组成 insert、search 和 startsWith 调用次数 总计 不超过3*104次classTrie{public:Trie(){root=newTrieNode();}classTrieNode// 内部类{public:boolisWord=false;TrieNode*children[26];// 数组TrieNode(){for(inti=0;i<26;i++){children[i]=nullptr;}}~TrieNode(){for(inti=0;i<26;i++){deletechildren[i];children[i]=nullptr;}}};/** Inserts a word into the trie. */voidinsert(string word){TrieNode*node=root;for(inti=0;i<word.length();i++){intindex=word[i]-'a';if(node->children[index]==nullptr){node->children[index]=newTrieNode();}node=node->children[index];}node->isWord=true;}/** Returns if the word is in the trie. */boolsearch(string word){TrieNode*node=root;for(inti=0;i<word.length();i++){intindex=word[i]-'a';if(node->children[index]==nullptr){returnfalse;}node=node->children[index];}returnnode->isWord;}/** Returns if there is any word in the trie that starts with the given prefix. */boolstartsWith(string prefix){TrieNode*node=root;for(inti=0;i<prefix.length();i++){intindex=prefix[i]-'a';if(node->children[index]==nullptr){returnfalse;}node=node->children[index];}returntrue;}private:TrieNode*root;};