AcWing
  • 首页
  • 课程
  • 题库
  • 更多
    • 竞赛
    • 题解
    • 分享
    • 问答
    • 应用
    • 校园
  • 关闭
    历史记录
    清除记录
    猜你想搜
    AcWing热点
  • App
  • 登录/注册

练习

作者: 作者的头像   Tie ,  2019-09-09 16:01:56 ,  所有人可见 ,  阅读 1370


1


  • 题目
    实现一个trie树,要求实现addWord, removeWord, hasWorld, enumulateWord四个函数

思路:leetcode 208 变形

/*
 * @lc app=leetcode id=208 lang=cpp
 *
 * [208] Implement Trie (Prefix Tree)
 *
 * https://leetcode.com/problems/implement-trie-prefix-tree/description/
 *
 * algorithms
 * Medium (39.88%)
 * Likes:    1838
 * Dislikes: 35
 * Total Accepted:    199.8K
 * Total Submissions: 494.5K
 * Testcase Example:  '["Trie","insert","search","search","startsWith","insert","search"]\n[[],["apple"],["apple"],["app"],["app"],["app"],["app"]]'
 *
 * Implement a trie with insert, search, and startsWith methods.
 * 
 * Example:
 * 
 * 
 * Trie trie = new Trie();
 * 
 * trie.insert("apple");
 * trie.search("apple");   // returns true
 * trie.search("app");     // returns false
 * trie.startsWith("app"); // returns true
 * trie.insert("app");   
 * trie.search("app");     // returns true
 * 
 * 
 * Note:
 * 
 * 
 * You may assume that all inputs are consist of lowercase letters a-z.
 * All inputs are guaranteed to be non-empty strings.
 * 
 * 
 */

代码

class Trie 
{
public:
    struct Node
    {
        bool is_end;
        Node *son[26];
        Node()
        {
            is_end = false;
            for (int i = 0; i < 26; i ++ ) son[i] = NULL;
        }
    }*root; // define a return type
    //Error: error: new types may not be defined in a return type

    Trie()
    {
        root = new Node();
    }

    void insert(string word)
    {
        auto p = root;
        for (auto c: word)
        {
            int u = c - 'a';
            if (p->son[u] == NULL) p->son[u] = new Node();
            p = p->son[u]; //这里不是else
        }
        p->is_end = true;
    }

    bool search(string word)
    {
        auto p = root;
        for (auto c: word)
        {
            int u = c - 'a';
            if (p->son[u] == NULL) return false;
            else p = p->son[u];   
        }
        return p->is_end;
    }

    bool startsWith(string prefix)
    {
        auto p = root;
        for (auto c: prefix)
        {
            int u = c - 'a';
            if (p->son[u] == NULL) return false;
            else p = p->son[u];
        }
        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 评论

App 内打开
你确定删除吗?
1024
x

© 2018-2025 AcWing 版权所有  |  京ICP备2021015969号-2
用户协议  |  隐私政策  |  常见问题  |  联系我们
AcWing
请输入登录信息
更多登录方式: 微信图标 qq图标 qq图标
请输入绑定的邮箱地址
请输入注册信息