数据结构_trie_搜索实现

import javafx.concurrent.WorkerStateEvent;

import java.util.TreeMap;

class WordDictionary {
    private class Node{
        public boolean isend;
        public TreeMap<Character,Node> next;
        public Node(){this(false); }
        public Node(boolean isend){
            this.isend=isend;
            this.next = new TreeMap<>();
        }
    }
    private Node root;
    /** Initialize your data structure here. */
    public WordDictionary() {
        root = new Node();
    }

    /** Adds a word into the data structure. */
    public void addWord(String word) {
        Node cur = root;
        for(int i = 0;i<word.length();i++){
            Character w = word.charAt(i);
            if(cur.next.get(w)==null)
                cur.next.put(w,new Node());
            cur = cur.next.get(w);
        }
        cur.isend = 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);

    }
    //在当前根下查找 是否存在某char
    private boolean search(Node node,String word,int index){
        //终止条件 当前index 超过了 word的长度
        if(index>=word.length())
            return node.isend;
        //递归
        //判断是不是 .
        Character w = word.charAt(index);
        if(w!='.')
            //不是 .
            return node.next.get(w) != null && search(node.next.get(w), word, index + 1);
        else{
            //是 . 通配符 遍历所有的next
            for(Character c:node.next.keySet())
                if(search(node.next.get(c),word,index+1))
                    return true;
            return false;
        }
    }
}

/**
 * Your WordDictionary object will be instantiated and called as such:
 * WordDictionary obj = new WordDictionary();
 * obj.addWord(word);
 * boolean param_2 = obj.search(word);
 */

猜你喜欢

转载自blog.csdn.net/weixin_41676078/article/details/81536481
今日推荐