您的位置:首页 > 其它

[LeetCode 211] Add and Search word -- Data Structure Design

2015-08-25 14:07 330 查看
<p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 10px; color: rgb(51, 51, 51); font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 14px; line-height: 30px;">Design a data structure that supports the following two operations:</p><pre style="box-sizing: border-box; overflow: auto; font-family: Menlo, Monaco, Consolas, 'Courier New', monospace; font-size: 13px; padding: 9.5px; margin-top: 0px; margin-bottom: 10px; line-height: 1.42857143; color: rgb(51, 51, 51); word-break: break-all; word-wrap: break-word; border: 1px solid rgb(204, 204, 204); border-radius: 4px; background-color: rgb(245, 245, 245);">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
.


利用trie prefix tree。
TreeNode root = new TreeNode();
    // Adds a word into the data structure.
    public void addWord(String word) {
        Map<Character, TreeNode> children = root.children; 
        for(int i=0;i<word.length();i++){
            char w = word.charAt(i);
            TreeNode t;
            if(children.containsKey(w)){
                t = children.get(w);
            }else{
                t = new TreeNode(w);
                children.put(w, t);
            }
            children = t.children;
            if(i == word.length()-1)
                t.leaf = true;
        }
    }

    public boolean searchNode(String word, TreeNode node){
        if(node == null) return false;
        if(word.isEmpty()) return node.leaf;
        Map<Character, TreeNode> children = node.children;
        char c = word.charAt(0);
        TreeNode t=null;
        if(c == '.'){
            for(char key :children.keySet()){
                if(searchNode(word.substring(1), children.get(key))) return true;
            }
            return false;
        } else if(!children.containsKey(c)){
            return false;
        }else {
            t = children.get(c);
            return searchNode(word.substring(1), t);
        }
    }
    // 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 searchNode(word, root);
    }
    
    class TreeNode{
        char c;
        boolean leaf=false;
        Map<Character, TreeNode> children = new HashMap<>();
        public TreeNode (char c){
            this.c = c;
        }
        public TreeNode(){
            
        }
    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: