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.

 

 

基于字典树来设计,还可以优化,把string转换成char[]即可。

 

public class WordDictionary {
    
    public WordDictionary[] words;
    public boolean isWord;
    
    /** Initialize your data structure here. */
    public WordDictionary() {
        words = new WordDictionary[26];
    }
    
    /** Adds a word into the data structure. */
    public void addWord(String word) {
        WordDictionary[] wordCh = words;
        for (int i = 0; i < word.length(); i++){
            int pos = (int) (word.charAt(i) - 'a');
            if (wordCh[pos] == null){
                wordCh[pos] = new WordDictionary();
            }
            if (i == word.length() - 1){
                wordCh[pos].isWord = true;
            }
            wordCh = wordCh[pos].words;
        }
    }
    
    /** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. 
        注意search与startsWith的区别
    */
    public boolean search(String word) {
        
        if (word.length() == 0){
            return isWord;
        }
        if (word.charAt(0) == '.'){
            for (int i = 0; i < 26; i++){
                if (words[i] != null && words[i].search(word.substring(1, word.length()))){
                    return true;
                }
            }
            return false;
        }
        if (words[word.charAt(0) - 'a'] == null){
            return false;
        } else {
            return words[word.charAt(0) - 'a'].search(word.substring(1, word.length()));
        }
    }
}

/**
 * Your WordDictionary object will be instantiated and called as such:
 * WordDictionary obj = new WordDictionary();
 * obj.addWord(word);
 * boolean param_2 = obj.search(word);
 */