Trie Tree

Problem Description

Implement a Trie(prefix tree) and support the following operations:

  1. insert: insert a string into the Trie.
  2. search: return true if the queried string has been inserted into the Trie.
  3. startsWith: return true if there is any string in the Trie that starts with the given prefix.

Examples

Input:
4
insert abc
search abc
search ab
startsWith ab
Output:
True
False
True

Note

  1. You may assume that all strings in the test cases consist of lowercase letters a-z.
  2. All inputs are guaranteed to be non-empty strings.
  3. A word is a prefix of itself. (apple startsWith apple)

Reference Code

// You can add any members in the class.
// The following 4 functions will be called in test program.
#include <iostream>
#include <vector>
#include <cstring>
using namespace std;

class Trie
{
private:
    vector<Trie*> kids;
    bool isEnd;

    Trie* searchPrefix(char* prefix)
    {
        Trie* node=this;

        int len=strlen(prefix);
        for(int i=0;i<len;i++)
        {
            char ch=prefix[i];
            ch-='a';
            if(node->kids[ch]==nullptr)
            {
                return nullptr;
            }
            node = node->kids[ch];
        }
        return node;
    }

public:
    Trie():kids(26),isEnd(false)
    {
        // TODO
    }

    void insert(char* word)
    {
        // TODO
        Trie* node=this;

        int len=strlen(word);
        for(int i=0;i<len;i++)
        {
            char ch=word[i];
            ch-='a';
            if(node->kids[ch]==nullptr)
            {
                node->kids[ch]=new Trie();
            }
            node=node->kids[ch];
        }
        node->isEnd=true;
    }

    bool search(char* word)
    {
        // TODO
        Trie* node=this->searchPrefix(word);
        return node!=nullptr&&node->isEnd;
    }

    bool startsWith(char* prefix)
    {
        // TODO
        return this->searchPrefix(prefix)!=nullptr;
    }
};

指路:leetcode208

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值