leetcode [211] Add and Search Word - Data structure design

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.

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.

题目大意:

判断一个词是否在字典中出现过,其中词包括a-z和.这27个字符,其中.可以匹配任意字符。

解法:

使用前缀树做,根据单词建立一颗前缀树。

java:

class TrieNode{
    public char val;
    public boolean isWord;
    public TrieNode[] children=new TrieNode[26];
    TrieNode(){}
    TrieNode(char val){
        this.val=val;
    }
}

class WordDictionary {
    private TrieNode root;

    /** Initialize your data structure here. */
    public WordDictionary() {
        root=new TrieNode(' ');
    }

    /** Adds a word into the data structure. */
    public void addWord(String word) {
        TrieNode node=root;
        for(int i=0;i<word.length();i++) {
            char c = word.charAt(i);
            if (node.children[c - 'a'] == null) {
                node.children[c - 'a']=new TrieNode(c);
            }
            if(i==word.length()-1) node.children[c - 'a'].isWord=true;
            node = node.children[c - 'a'];
        }
    }

    private boolean helper(String word,TrieNode curNode,int index){
        if(index==word.length()){
            if(curNode.isWord) return true;
            else return false;
        }
        char c=word.charAt(index);
        if(c!='.' && curNode.children[c-'a']!=null){
            return helper(word,curNode.children[c-'a'],index+1);
        }else if(c!='.' && curNode.children[c-'a']==null){
            return false;
        }else{
            for(int i=0;i<26;i++){
                if(curNode.children[i]!=null){
                    if(helper(word,curNode.children[i],index+1)) return true;
                }
            }
            return false;
        }
    }

    /** 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) {
        TrieNode node=root;
        return helper(word,root,0);
    }
}

  

posted @ 2019-04-28 10:36  小白兔云  阅读(131)  评论(0)    收藏  举报