码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode-Add and Search Word

时间:2016-09-10 06:38:19      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:

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");

 

LeetCode-Add and Search Word

标签:

原文地址:http://www.cnblogs.com/lishiblog/p/5858569.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!