字典树
C++实现trid
class TrieNode{ public: TrieNode():End(false), R(26){ links.resize(R); } void setEnd(){ End = true; } bool isEnd(){ return End; } bool containsKey(char key){ return links[key - 'a'] != nullptr; } void put(char key, TrieNode* node){ links[key - 'a'] = node; } TrieNode* get(char key){ return links[key - 'a']; } private: vector<TrieNode*> links; bool End; int R; }; class Trie { public: /** Initialize your data structure here. */ TrieNode* root; Trie(){ root = new TrieNode(); } /** Inserts a word into the trie. */ void insert(string word) { TrieNode* p = root; for(int i = 0; i < word.size(); ++i) { if(!p->containsKey(word[i])) { p->put(word[i], new TrieNode()); } p = p->get(word[i]); } p->setEnd(); } TrieNode* searchPrefix(string word) { TrieNode* p = root; for(int i = 0; i < word.size(); ++i) { if (p->containsKey(word[i])) { p = p->get(word[i]); } else { return nullptr; } } return p; } /** Returns if the word is in the trie. */ bool search(string word) { TrieNode* node = searchPrefix(word); return node != nullptr && node->isEnd(); } /** Returns if there is any word in the trie that starts with the given prefix. */ bool startsWith(string prefix) { TrieNode* node = searchPrefix(prefix); return node != nullptr; } };
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步