Add and Search Word - Data structure design

来源:互联网 发布:万方数据库与中国知网 编辑:程序博客网 时间:2024/06/04 18:21

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") -> falsesearch("bad") -> truesearch(".ad") -> truesearch("b..") -> true

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

click to show hint.

You should be familiar with how a Trie works. If not, please work on this problem: Implement Trie (Prefix Tree) first.
思路:这道题如果做过之前的那道 Implement Trie (Prefix Tree) 实现字典树(前缀树)的话就没有太大的难度了,还是要用到字典树的结构,唯一不同的地方就是search的函数需要重新写一下,因为这道题里面'.'可以代替任意字符,所以一旦有了'.',就需要查找所有的子树,只要有一个返回true,整个search函数就返回true,典型的DFS的问题,其他部分跟上一道实现字典树没有太大区别,代码如下:

public class WordDictionary {    private class TrieNode{        TrieNode[] array;        boolean isword;        public TrieNode(){            array = new TrieNode[26];            isword = false;        }    }    private TrieNode root = new TrieNode();    // Adds a word into the data structure.    public void addWord(String word) {        if(word == null) return;        TrieNode node = root;        for(int i=0; i<word.length(); i++){            char c = word.charAt(i);            if(node.array[c-'a'] == null){                node.array[c-'a'] = new TrieNode();                node = node.array[c-'a'];            } else {                node  = node.array[c-'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) {        if(word == null || word.length() == 0) return false;        return find(word, root, 0);    }        public boolean find(String word, TrieNode root, int index) {        if(root == null || (index == word.length() && !root.isword)) return false;        if(index == word.length() && root.isword) return true;        char c = word.charAt(index);        if(c == '.'){            for(int i=0; i<26; i++){                if(find(word, root.array[i], index+1)){                    return true;                }            }            return false;        } else {            return find(word, root.array[c-'a'], index+1);        }    }}// Your WordDictionary object will be instantiated and called as such:// WordDictionary wordDictionary = new WordDictionary();// wordDictionary.addWord("word");// wordDictionary.search("pattern");


0 0
原创粉丝点击