首页 > 其他 > 详细

208. Implement Trie (Prefix Tree)

时间:2016-09-22 01:11:46      阅读:262      评论:0      收藏:0      [点我收藏+]

Implement a trie with insertsearch, and startsWith methods.

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

 

 

class TrieNode {
    public TrieNode[] Child {get;set;}
    public bool EndWord {get;set;}
    // Initialize your data structure here.
    public TrieNode() {
        Child = new TrieNode[26];
        EndWord = false;
    }
}

public class Trie {
    private TrieNode root;

    public Trie() {
        root = new TrieNode();
    }

    // Inserts a word into the trie.
    public void Insert(String word) {
        var sentinel = root;
        for(int i =0;i<word.Length;i++)
        {
            if(sentinel.Child[word[i]-a] == null) sentinel.Child[word[i]-a] = new TrieNode();
            sentinel = sentinel.Child[word[i]-a];
        }
        sentinel.EndWord = true;
    }

    // Returns if the word is in the trie.
    public bool Search(string word) {
         var sentinel = root;
         for(int i =0;i<word.Length;i++)
        {
             if(sentinel.Child[word[i]-a] == null) return false;
             sentinel = sentinel.Child[word[i]-a];
        }
        return sentinel.EndWord;
        
    }

    // Returns if there is any word in the trie
    // that starts with the given prefix.
    public bool StartsWith(string word) {
         var sentinel = root;
         for(int i =0;i<word.Length;i++)
        {
             if(sentinel.Child[word[i]-a] == null) return false;
             sentinel = sentinel.Child[word[i]-a];
        }
        return true;
    }
}

// Your Trie object will be instantiated and called as such:
// Trie trie = new Trie();
// trie.Insert("somestring");
// trie.Search("key");

 

208. Implement Trie (Prefix Tree)

原文:http://www.cnblogs.com/renyualbert/p/5894608.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!