Add and Search Word

Design a data structure that supports the following two operations:

void addWord(word)
boolean 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.

Analysis

在Implement Trie的基础之上,应用Trie。不同之处在于对于pattern的匹配,需要进行backtracking,也就是利用DFS,对于匹配了'.'的那个TrieNode的每一个children都循环遍历,如果有一个为true,则说明找到一个match,即可返回true。

Solution

class TrieNode {
    public boolean isLeaf;
    public TrieNode[] children;

    public TrieNode() {
        this.children = new TrieNode[26];
    }
}

public class WordDictionary {

    private TrieNode root;

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

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

    private boolean match(TrieNode p, String word, int k) {
        if (k == word.length()) {
            return p.isLeaf;
        }
        if (word.charAt(k) == '.') {
            for (int i = 0; i < p.children.length; i++) {
                if (p.children[i] != null) {
                    if (match(p.children[i], word, k + 1)) {
                        return true;
                    }
                }
            }
        } else {
            int index = word.charAt(k) - 'a';
            return p.children[index] != null && match(p.children[index], word, k + 1);
        }
        return false;
    }
}

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

(126ms 54.49%)

Reference

Last updated

Was this helpful?