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剩余部分。其他情况与正常的字典树相同。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容