zoukankan      html  css  js  c++  java
  • 211. Add and Search Word

    Design a data structure that supports the following two operations:

    void addWord(word)
    bool search(word)
    

    search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter.

    For example:

    addWord("bad")
    addWord("dad")
    addWord("mad")
    search("pad") -> false
    search("bad") -> true
    search(".ad") -> true
    search("b..") -> true
    

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

    public 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 WordDictionary {
        public TrieNode root  = new TrieNode();
        // Adds a word into the data structure.
        public void AddWord(String word) {
            var sentinel = root;
            foreach(char w in word)
            {
                if(sentinel.Child[w-'a'] == null) sentinel.Child[w-'a'] = new TrieNode();
                sentinel = sentinel.Child[w-'a'];
            }
            sentinel.EndWord = true;
            
        }
    
        // Returns if the word is in the data structure. A word could
        // contain the dot character '.' to represent any one letter.
        public bool Search(string word) {
            return Search(word,root,0);
        }
        
        public bool Search(string word, TrieNode t, int index)
        {
            if(index == word.Length) return t.EndWord;
            if(word[index] == '.')
            {
                foreach(var c in t.Child)
                {
                    if(c!= null && Search(word,c,index+1)) return true;
                }
                return false;
            }
            if(t== null ||t.Child[word[index]-'a'] == null) return false;
            return Search(word,t.Child[word[index]-'a'],index+1);
        }
    }
    
    // Your WordDictionary object will be instantiated and called as such:
    // WordDictionary wordDictionary = new WordDictionary();
    // wordDictionary.AddWord("word");
    // wordDictionary.Search("pattern");
  • 相关阅读:
    Vue.Draggable实现拖拽效果(快速使用)
    1.从面向过程到面向对象的过渡
    微信支付流程
    2.js原型的基本概念
    POST和GET请求的区别
    vue-router2.0
    vue列表渲染,以及鼠标点击改变样式的问题
    复杂数组结构的深拷贝
    高德地图将字符串地址转为经纬度的一个demo
    数组对象排序
  • 原文地址:https://www.cnblogs.com/renyualbert/p/5894660.html
Copyright © 2011-2022 走看看