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.

    Use Tire

    public class WordDictionary {
        class TrieNode {
            Map<Character, TrieNode> map;
            boolean isWord;
            public TrieNode(){
                map = new HashMap<>();
                isWord = false;
            }
        }
        private TrieNode root;
        public WordDictionary(){
            root = new TrieNode();
        }
        // Adds a word into the data structure.
        public void addWord(String word) {
            TrieNode node = root;
            for(char c : word.toCharArray()){
                if(!node.map.containsKey(c)){
                    node.map.put(c, new TrieNode());
                }
                node =  node.map.get(c);
            }
            node.isWord = true;
        }
    
        // Returns if the word is in the data structure. A word could
        // contain the dot character '.' to represent any one letter.
        public boolean search(String word) {
            return dfs(word.toCharArray() , 0 , root);
        }
        
        public boolean dfs(char[] words, int deep , TrieNode root){
            if(deep == words.length){
                return root.isWord;
            }
            if(words[deep] == '.'){
                for(char s : root.map.keySet()){
                     if(dfs(words , deep+1 , root.map.get(s)))
                            return true;
                }
            }
            else{
                return root.map.containsKey(words[deep]) && dfs(words , deep+1 , root.map.get(words[deep]));
            } 
            return false;
        }
    }
    
    // Your WordDictionary object will be instantiated and called as such:
    // WordDictionary wordDictionary = new WordDictionary();
    // wordDictionary.addWord("word");
    // wordDictionary.search("pattern");
  • 相关阅读:
    新院址运行统计
    游标使用之四
    游标使用之三
    css基础知识
    javascript基础知识
    [每日一题2020.06.20]BFS
    白嫖一个免费域名并解析到博客园
    [每日一题2020.06.19]leetcode #84 #121 单调栈
    操作系统---文件管理
    [每日一题2020.06.18]leetcode #3 hash_map实现滑动窗口
  • 原文地址:https://www.cnblogs.com/joannacode/p/6130444.html
Copyright © 2011-2022 走看看