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.

For example:
addWord("bad")
addWord("dad")
addWord("mad")
search("pad") -> false
search("bad") -> true
search(".ad") -> true
search("b..") -> true

思路:
如果去掉了特殊字符.就是一道典型的trie樹解法題目,所以關鍵是如何解決特殊字符.的情況。
自己第一次想的是,每次add一個字符的時候同樣add一個.字符,即把.當做第27個字符來看待,但是增加第一個.字符之后,如何解決后續字符在.節點的分支是個問題,同樣在搜索的方法實現上也很復雜,自己沒有想清楚怎么解決。
因此另一種實現方法,就是暴力的,如果遇見了.,則在當前節點的所有子節點進行搜索,如果字符串很長,并且trie樹很茂盛,時間復雜度會很高,但是被accepted了!

class WordDictionary {

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

TrieNode root;

public WordDictionary() {
    this.root = new TrieNode();
}

/** Adds a word into the data structure. */
public void addWord(String word) {
    TrieNode dummy = this.root;
    for (int i = 0; i < word.length(); i++) {
        char c = word.charAt(i);
        if (dummy.children[c - 'a'] == null) {
            dummy.children[c - 'a'] = new TrieNode();
        }
        dummy = dummy.children[c - 'a'];
    }
    dummy.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 this._searchHelper(word, 0, this.root);
}

private boolean _searchHelper(String word, int pos, TrieNode node) {
    if (pos == word.length()) {
        return node.isWord;
    }

    char c = word.charAt(pos);
    if (word.charAt(pos) != '.') {
        if (node.children[c - 'a'] == null) {
            return false;
        }
        return _searchHelper(word, pos + 1, node.children[c - 'a']);
    } else {
        for (int i = 0; i < 26; i++) {
            if (node.children[i] != null && _searchHelper(word, pos + 1, node.children[i])) {
                return true;
            }
        }
        return false;
    }
}

}

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容