zoukankan      html  css  js  c++  java
  • LeetCode 208

    一、问题描述

    Description:

    Implement a trie with insert, search, and startsWith methods.

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


    二、解题报告

    什么是trie树,trie树有哪些应用,怎么实现trie树,请看《Trie树的应用与实现》。

    直接上代码:

    class TrieNode {
    public:
        bool iskey;   // 标记该节点是否代表关键字
        TrieNode *children[26]; // 各个子节点
        TrieNode() {
            iskey = false;
            for(int i=0; i<26; ++i)
                children[i] = NULL;
        }
    };
    
    class Trie {
    public:
        Trie() {
            root = new TrieNode();
        }
    
        // 插入一个单词到trie树中
        void insert(string s) {
            TrieNode* node = root;
            for(int i=0; i<s.size(); ++i)
            {
                if(node->children[s[i]-'a'] == NULL)
                {
                    node->children[s[i]-'a'] = new TrieNode();
                }
                node = node->children[s[i]-'a'];
            }
            node->iskey = true;
        }
    
        // 搜索关键字key是否在trie树中
        bool search(string key) {
            TrieNode* node = root;
            for(int i=0; i<key.size(); ++i)
                if(node!=NULL)
                    node = node->children[key[i]-'a'];
                else
                    break;
    
            if(node == NULL)
                return false;
            else
                return node->iskey;
        }
    
        // 判断trie树中是否有以prefix为前缀的单词
        bool startsWith(string prefix) {
            TrieNode* node = root;
            for(int i=0; i<prefix.size(); ++i)
                if(node!=NULL)
                    node = node->children[prefix[i]-'a'];
                else
                    break;
    
            if(node == NULL)
                return false;
            else
                return true;
        }
    
    private:
        TrieNode* root;
    };







    LeetCode答案源代码:https://github.com/SongLee24/LeetCode

  • 相关阅读:
    [Python3网络爬虫开发实战] 3.1.3-解析链接
    pusher-http-go
    gopush-cluster 架构
    消息队列 redis vs nsq
    redis资料
    golang+websocket
    golang之flag.String
    Linux环境下安装mysql
    golang版的crontab
    golang实现wav文件转换为mp3文件
  • 原文地址:https://www.cnblogs.com/songlee/p/5738072.html
Copyright © 2011-2022 走看看