zoukankan      html  css  js  c++  java
  • 208. Implement Trie (Prefix Tree)

    class Trie {
    
        Trie[] children=new Trie[26];
        
        boolean isWord=false;
        
        /** Initialize your data structure here. */
        public Trie() {
            
        }
        
        /** Inserts a word into the trie. */
        public void insert(String word) {
            if(word.length()==0)
            {
                isWord=true;
                return;
            }
            int idx=word.charAt(0)-'a';
            if(children[idx]==null)
                children[idx]=new Trie();
            children[idx].insert(word.substring(1));
        }
        
        /** Returns if the word is in the trie. */
        public boolean search(String word) {
            if(word.length()==0)
                return isWord;
            int idx=word.charAt(0)-'a';
            if(children[idx]!=null)
                return children[idx].search(word.substring(1));
            return false;
        }
        
        /** Returns if there is any word in the trie that starts with the given prefix. */
        public boolean startsWith(String prefix) {
            if(prefix.length()==0)
                return true;
            int idx=prefix.charAt(0)-'a';
            if(children[idx]!=null)
                return children[idx].startsWith(prefix.substring(1));
            return false;
        }
    }
    

      

  • 相关阅读:
    第八周作业
    第八周上机练习
    第七周作业
    第七次上机练习
    第六周作业
    4.9上机作业
    第五周作业
    第四次JAVA作业
    第四周作业
    第十六次作业
  • 原文地址:https://www.cnblogs.com/asuran/p/7796616.html
Copyright © 2011-2022 走看看