赞
踩
本篇博客主要讲解对LeetCode中Tier类型题的解法归纳和思考和对算法本身的一些理解。
实现一个 Trie (前缀树),包含 insert, search, 和 startsWith 这三个操作。
示例:
Trie trie = new Trie();
trie.insert("apple");
trie.search("apple"); // 返回 true
trie.search("app"); // 返回 false
trie.startsWith("app"); // 返回 true
trie.insert("app");
trie.search("app"); // 返回 true
说明:
解题思路: 第一次做Tier类型题,我们以此题打开对Tier的理解,首先我们要明确Tier的几点特点(我之前对Tier概念理解不深时,对下述特点有点迷糊):
理解了上述两点构造Tier就不会出错了,请看下面代码,代码的解题思路参考于这篇博客。
class TierNode { public: TierNode* child[26]; bool isWord; TierNode() : isWord(false) { for (auto &a : child) { a = nullptr; } } }; class Trie { public: /** Initialize your data structure here. */ Trie() { root = new TierNode(); } /** Inserts a word into the trie. */ void insert(string word) { TierNode *p = root; for (auto &w : word) { int idx = w - 'a'; if (!p->child[idx]) p->child[idx] = new TierNode(); p = p->child[idx]; } p->isWord = true; } /** Returns if the word is in the trie. */ bool search(string word) { TierNode *p = root; for (auto &w : word) { int idx = w - 'a'; if (!p->child[idx]) return false; p = p->child[idx]; } return p->isWord; } /** Returns if there is any word in the trie that starts with the given prefix. */ bool startsWith(string prefix) { TierNode *p = root; for (auto &w : prefix) { int idx = w - 'a'; if (!p->child[idx]) return false; p = p->child[idx]; } return true; } private: TierNode* root; }; /** * Your Trie object will be instantiated and called as such: * Trie* obj = new Trie(); * obj->insert(word); * bool param_2 = obj->search(word); * bool param_3 = obj->startsWith(prefix); */
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。