LeetCode 208:实现Trie(前缀树)——C#实现

因为了解红点系统要了解前缀树,这里转载一篇言简意赅的文章


题目:

实现一个 Trie (前缀树),包含 insert, search, 和 startsWith 这三个操作。

示例:

Trie trie = new Trie();
 
trie.insert("apple");
trie.search("apple");   // 返回 true
trie.search("app");     // 返回 false
trie.startsWith("app"); // 返回 true
trie.insert("app");   
trie.search("app");     // 返回 true

说明:

  • 你可以假设所有的输入都是由小写字母 a-z 构成的。
  • 保证所有输入均为非空字符串。

一开始没听说过什么是前缀树,觉得这题好简单,直接使用string的函数实现了,发现对于大量的字符串处理,string的封装函数处理性能完全不够,后来百度才知道原来前缀树是一个名词,详细解释请见链接:trie树(前缀树)这个里面解释的非常清楚。

看完前缀树的解释,然后又看了LeetCode上大家的评论,给出C#实现的前缀树。

执行用时 : 344 ms,Implement Trie (Prefix Tree)的C#提交中击败了67.74% 的用户
 
内存消耗 : 46.8 MB,Implement Trie (Prefix Tree)的C#提交中击败了22.22% 的用户
class Trie
    {
        private class Node
        {
            public Node[] children;
            public bool isEnd = false;
            public Node()
            {
                children = new Node[26];
                isEnd = false;
            }
        }
 
        private Node rootNode = null;
        /** Initialize your data structure here. */
        public Trie()
        {
            rootNode = new Node();
        }
 
        /** Inserts a word into the trie. */
        public void Insert(String word)
        {
            Node currNode = rootNode;
            for (int i = 0; i < word.Length; i++)
            {
                if (currNode.children[word[i] - 'a'] == null)
                {
                    currNode.children[word[i] - 'a'] = new Node();
                }
                currNode = currNode.children[word[i] - 'a'];
            }
            currNode.isEnd = true;                    
        }
 
        /** Returns if the word is in the trie. */
        public bool Search(String word)
        {
            Node currNode = rootNode;
            for (int i = 0; i < word.Length; i++)
            {
                if (currNode.children[word[i] - 'a'] == null)
                {
                    return false;
                }
                currNode = currNode.children[word[i] - 'a'];
            }
            return currNode.isEnd;          
        }
 
        /** Returns if there is any word in the trie that starts with the given prefix. */
        public bool StartsWith(String prefix)
        {
            Node currNode = rootNode;
            for (int i = 0; i < prefix.Length; i++)
            {
                if (currNode.children[prefix[i] - 'a'] == null)
                {
                    return false;
                }
                currNode = currNode.children[prefix[i] - 'a'];
            }
            return true;
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值