leetcode 211. 添加与搜索单词 - 数据结构设计

在这里插入图片描述

class WordDictionary {
    private Node root;
        private class Node{
        public boolean isWord;
        public TreeMap<Character,Node>next;//多叉树
        public Node(boolean isWord){
            this.isWord=isWord;
            next=new TreeMap<>();
        }
        public Node(){
            // this(false);相当于调用构造器NOde(boolen is Word)
            this.isWord=false;
            next=new TreeMap<>();
        }

    }
    /** Initialize your data structure here. */
    public WordDictionary() {
        root=new Node();
    }
    
    /** Adds a word into the data structure. */
    public void addWord(String word) {
         _insert(root,0,word);
    }
    // 从cur 节点构建word[index:]求word[0:]
    public  void _insert(Node cur,int i,String word){
       if(i==word.length())
         {
             cur.isWord=true;
             return ;
         }
        //cur 走到了word最后一个字符,不一定是叶子结点,如panda(中pan 为一个单词)
        char c=word.charAt(i);
        if(cur.next.get(c)==null)
            cur.next.put(c,new Node());
        cur=cur.next.get(c);//走到c结点
        _insert(cur,i+1,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 _search(word,root,0);
    }
    public boolean _search(String word,Node cur,int i){
        if(i==word.length()) return cur.isWord;
            char c=word.charAt(i);
            if(c!='.'){
                 if(cur.next.get(c)==null) return false;
                    cur=cur.next.get(c);
                 return _search(word, cur, i+1);
            }
            else {
                for(char nextchar:cur.next.keySet()){
                if(_search(word,cur.next.get(nextchar),i+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);
 */
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值