专栏首页计算机视觉与深度学习基础Leetcode 208 Implement Trie (Prefix Tree) 字典树

Leetcode 208 Implement Trie (Prefix Tree) 字典树

Implement a trie with insertsearch, and startsWith methods.

Note: You may assume that all inputs are consist of lowercase letters a-z.

实现字典树,包括插入、查询整词、查询前缀的函数。

class node
{
    public:
    int flag;
    node* next[26];
    node(int x = 0)
    {
        flag = x;
        memset(next, 0, sizeof(next));
    }
};
class Trie {
public:
    /** Initialize your data structure here. */
    node* root;
    Trie() {
        root = new node();
    }
    /** Inserts a word into the trie. */
    void insert(string word) 
    {
        node* p = root;
        for(int i = 0; i < word.size(); i++)
        {
            if(!p->next[word[i] - 'a']) p->next[word[i] - 'a'] = new node();
            p = p->next[word[i] - 'a'];
        }
        p->flag = 1;
    }
    /** Returns if the word is in the trie. */
    bool search(string word) 
    {
        node* p = root;
        for(int i = 0; i < word.size(); i++)
        {
            if(!p->next[word[i] - 'a']) return false;
            p = p->next[word[i] - 'a'];
        }
        return p->flag == 1;
    }
    /** Returns if there is any word in the trie that starts with the given prefix. */
    bool startsWith(string prefix) 
    {
        node* p = root;
        for(int i = 0; i < prefix.size(); i++)
        {
            if(!p->next[prefix[i] - 'a']) return false;
            p = p->next[prefix[i] - 'a'];
        }
        return true;
    }
};

/**
 * 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);
 */

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • Leetcode 211 Add and Search Word - Data structure design

    Design a data structure that supports the following two operations: void addWor...

    triplebee
  • Leetcode 79 Word Search

    Given a 2D board and a word, find if the word exists in the grid. The word can...

    triplebee
  • Leetcode 134 Gas Station

    There are N gas stations along a circular route, where the amount of gas at sta...

    triplebee
  • Leetcode 211 Add and Search Word - Data structure design

    Design a data structure that supports the following two operations: void addWor...

    triplebee
  • 如何实现拼写纠错功能

    在使用搜索引擎时,当我们输入错误的关键词时,当然这里的错误是拼写错误,搜索引擎的下拉框中仍会显示以正确关键词为前前辍的提示,当你直接回车搜索错误的关键词时,搜索...

    somenzz
  • 【每周一坑】单词本 +【解答】三国演义中谁的存在感最强

    “每周一坑”这个系列在本教室的文章中,阅读量不算高。但我屡次在和读者沟通时听到说“我都有跟着每周一坑里的题在做”。这是个有意思的普遍现象:内容的价值和传播度并不...

    Crossin先生
  • Day11-字符串-无重复字符最长子串

    Q:已知一个字符串,求用该字符串的无重复字符的最长子串(有的要求求长度,今天直接求子串)

    BUPTrenyi
  • LeetCode 211. Add and Search Word - Data structure design(字典树)

    ShenduCC
  • LeetCode 208. Implement Trie (Prefix Tree)

    ShenduCC
  • HanLP《自然语言处理入门》笔记--2.词典分词

    笔记转载于GitHub项目:https://github.com/NLP-LOVE/Introduction-NLP

    mantch

扫码关注云+社区

领取腾讯云代金券