zoukankan      html  css  js  c++  java
  • LeetCode-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.

    Solution:

    public class WordDictionary {
        public class TrieNode{
            TrieNode[] childs;
            boolean hasWord;
            public TrieNode(){
                childs = new TrieNode[26];
                hasWord = false;
            }
        }
        
        TrieNode root;
        
        public WordDictionary(){
            root = new TrieNode();
        }
    
        // Adds a word into the data structure.
        public void addWord(String word) {
            TrieNode cur = root;
            for (char c : word.toCharArray()){
                if (cur.childs[c-'a']==null){
                    cur.childs[c-'a'] = new TrieNode();
                }
                cur = cur.childs[c-'a'];
            }
            cur.hasWord = 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 searchRecur(root,word,0);
        }
        
        public boolean searchRecur(TrieNode curNode, String word, int start){
            if (curNode==null){
                return false;
            }
            
            if (start>=word.length()){
                return curNode.hasWord;
            }
            
            char c = word.charAt(start);
            if (c=='.'){
                for (TrieNode child : curNode.childs)
                    if (searchRecur(child,word,start+1)){
                        return true;
                    }
                return false;
            } else {
                return searchRecur(curNode.childs[c-'a'],word,start+1);
            }
        }
    }
    
    // Your WordDictionary object will be instantiated and called as such:
    // WordDictionary wordDictionary = new WordDictionary();
    // wordDictionary.addWord("word");
    // wordDictionary.search("pattern");
  • 相关阅读:
    Sass--扩展继承
    Sass--混合宏的不足
    学习笔记47—PhotoShop技巧
    学习笔记46—如何使Word和EndNote关联
    学习笔记45—Linux压缩集
    学习笔记44—Linux下安装freesurfer
    学习笔记43—Linux安装集
    学习笔记42—Win7下安装Linux双系统
    学习笔记41—ttest误区
    学习笔记40—endnote点点滴滴
  • 原文地址:https://www.cnblogs.com/lishiblog/p/5858569.html
Copyright © 2011-2022 走看看