`

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

Note:
You may assume that all words are consist of lowercase letters a-z.

public class WordDictionary {
    public static class TrieNode {
        TrieNode[] children;
        boolean isLeaf;
        public TrieNode() {
            children = new TrieNode[26];
        }
    }
    
    private TrieNode root = new TrieNode();
    
    // Adds a word into the data structure.
    public void addWord(String word) {
        if(word == null || word.isEmpty()) return;
        TrieNode node = root;
        for(int i=0; i<word.length(); i++) {
            int j = word.charAt(i)-'a';
            if(node.children[j] == null) {
                node.children[j] = new TrieNode();
            }
            node = node.children[j];
        }
        node.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 search(root, word, 0);
    }
    
    private boolean search(TrieNode node, String word, int start) {
        if(node == null) return false;
        if(start == word.length()) return node.isLeaf;
        for(int i=start; i<word.length(); i++) {
            char c = word.charAt(i);
            if(c == '.') {
                for(int j=0; j<26; j++) {
                    if(search(node.children[j], word, i+1)) return true;
                }
                return false;
            } else {
                // node = node.children[c-'a'];
                // if(node == null) return false;
                return search(node.children[c-'a'], word, i+1);
            }
        }
        return false;//node.isLeaf;
    }
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics