211. Add and Search Word - Data structure design

Question

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

Code

class TrieNode {
    public boolean end;
    public TrieNode[] sons;
    public TrieNode() {
        end = false;
        sons = new TrieNode[26];
    }
}

class Trie {
    public TrieNode root;
    public Trie() {
        root = new TrieNode();
    }
    public void insert(String s) {
        if (s.length() == 0) return;
        TrieNode node = root;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (node.sons[c - 'a'] == null) {
                TrieNode newSon = new TrieNode();
                node.sons[c - 'a'] = newSon;
            } 
            node = node.sons[c - 'a'];
        }
        node.end = true;
    }
    
    public boolean search(String s) {
        if (s == null || s.length() == 0) return true;
        return searchHelper(s, root, 0);
    }
    
    public boolean searchHelper(String s, TrieNode node, int i) {
        if (i == s.length()) {
            if (node.end) return true;
            return false;
        }
        
        boolean result = false;
        char c = s.charAt(i);
        if (c == '.') {
            for (int j = 0; j < 26; j++) {
                if (node.sons[j] != null) {
                    if(searchHelper(s, node.sons[j], i + 1)) result = true;
                }
            }
        } else {
            if (node.sons[c - 'a'] == null) {
                result = false;
            } else {
                if (searchHelper(s, node.sons[c - 'a'], i + 1)) result = true;
            }
        }
        return result;
    }
}

public class WordDictionary {
    Trie t = new Trie();

    // Adds a word into the data structure.
    public void addWord(String word) {
        t.insert(word);
    }

    // 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 t.search(word);
    }
}

// Your WordDictionary object will be instantiated and called as such:
// WordDictionary wordDictionary = new WordDictionary();
// wordDictionary.addWord("word");
// wordDictionary.search("pattern");

Solution

用字典樹的insert()和search()實現。其中search()功能略做改動,當當前字符為‘.’時需遍歷所有葉子節點,若葉子節點不為null則遞歸地search剩余部分。其他情況與正常的字典樹相同。

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

推薦閱讀更多精彩內容