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;
        }
    }

猜你喜欢

转载自blog.csdn.net/weixin_43149049/article/details/122839609
今日推荐