Problem

Design a data structure that supports the following two operations: addWord(word) and 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.

Solution

public class WordDictionary {
    class TrieNode {
        char val;
        boolean isWord;
        TrieNode[] children;
        TrieNode() {
            children = new TrieNode[26];
        }
        TrieNode(char ch) {
            children = new TrieNode[26];
            val = ch;
        }
    }
    TrieNode 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 ch = word.charAt(i);
            if (node.children[ch-'a'] == null) node.children[ch-'a'] = new TrieNode(ch);
            node = node.children[ch-'a'];
        }
        node.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 helper(word, 0, root);
    }
    public boolean helper(String word, int pos, TrieNode node) {
        if (pos == word.length()) return node.isWord;
        char ch = word.charAt(pos);
        if (ch != '.') return node.children[ch-'a'] != null && helper(word, pos+1, node.children[ch-'a']);
        else {
            for (int i = 0; i < 26; i++) {
                if (node.children[i] != null && helper(word, pos+1, node.children[i])) return true;
            }
            return false;
        }
    }
}

linspiration
161 声望53 粉丝

引用和评论

0 条评论