leetcode-208-Implement Trie (Prefix Tree)

这道字典树就真的很简单了,一个插入、一个查找、还有一个查找前缀的,没有.的情况,所以也不需要用到递归,可以跟finaltest的1007一起理解,1007还要复杂一点。
#include <string.h>
using namespace std;
class TrieNode {
public:
    // Initialize your data structure here.
    TrieNode() {
        end = false;
        memset(child, 0, sizeof(child));
    }
    bool end;
    TrieNode *child[26];
};

class Trie {
public:
    Trie() {
        root = new TrieNode();
    }
    
    // Inserts a word into the trie.
    void insert(string word) {
        int counter = 0;
        TrieNode *current = root;
        while (counter != word.length()) {
            if (!current->child[word[counter] - 'a']) {
                current->child[word[counter] - 'a'] = new TrieNode();
            }
            current = current->child[word[counter] - 'a'];
            if (counter == word.length() - 1) {
                current->end = true;
            }
            counter++;
        }
    }
    
    // Returns if the word is in the trie.
    bool search(string word) {
        int counter = 0;
        TrieNode *current = root;
        while (counter != word.length()) {
            if (!current->child[word[counter] - 'a']) {
                return false;
            }
            current = current->child[word[counter] - 'a'];
            counter++;
        }
        return current->end;
    }
    
    // Returns if there is any word in the trie
    // that starts with the given prefix.
    bool startsWith(string prefix) {
        int counter = 0;
        TrieNode *current = root;
        while (counter != prefix.length()) {
            if (!current->child[prefix[counter] - 'a']) {
                return false;
            }
            current = current->child[prefix[counter] - 'a'];
            counter++;
        }
        return true;
    }
    
private:
    TrieNode* root;
};

// Your Trie object will be instantiated and called as such:
// Trie trie;
// trie.insert("somestring");
// trie.search("key");
int main(int argc, const char * argv[]) {
    // insert code here...
    Trie trie;
    trie.insert("ab");
    cout << trie.search("a") << endl;
    cout << trie.search("ab") << endl;
    cout << trie.startsWith("a") << endl;
    cout << trie.startsWith("ab") << endl;
    std::cout << "Hello, World!\n";
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值