示例#1
0
文件: Trie.cs 项目: 0x0all/ctci
 /* Takes a list of strings as an argument, and constructs a trie that stores these strings. */
 public Trie(string[] list)
 {
     _root = new TrieNode();
     foreach (string word in list) {
         _root.AddWord(word);
     }
 }
        /// Add the String passed in as argument to the trie, starting at a
        /// child node of this node. If any prefix of this String is already
        /// present in the trie starting from a child node of this node, only
        /// add the remaining part of the String to the trie, at the
        /// appropriate position in the trie.
        public void AddWord(string word)
        {
            if (string.IsNullOrEmpty(word))
            {
                return;
            }

            TrieNode child;
            char firstChar = word[0];

            TrieNode t = GetChild(firstChar);

            if (t == null)
            {
                child = new TrieNode(firstChar);
                _children.AddLast(child);
            }
            else
            {
                child = t;
            }

            if (word.Length > 1)
            {
                child.AddWord(word.Substring(1));
            }
            else
            {
                child.Terminates = true;
            }
        }