208 implement trie

208 impement trie 


// constructor TrieNode in class TrieNode cannot be applied to given types;

这个过程理解, 但是这个class , 放在哪不知道, 对这块没概念


class Trie {
  private TrieNode root;
  
  
  /** Initialize your data structure here. */
  public Trie(){
    root = new TrieNode();
    root.val = ' ';
  }
  
  
  /** Inserts a word into the trie. */
  public void insert(String word){
    TrieNode ws = root;
    for(int i = 0; i < word.length(); i++){
      char c = word.charAt(i);
      if(ws.children[c - 'a'] == null){
        ws.children[c - 'a'] = new TrieNode(c);
      }
      ws = ws.children[c - 'a'];
    }
    ws.isWord = true;
  }
  
  
  /** Returns if the word is in the trie. */
  public boolean search(String word){
    TrieNode ws = root;
    for(int i = 0; i < word.length(); i++){
      char c = word.charAt(i);
      if(ws.children[c - 'a'] == null){
        return false;
      }
      ws = ws.children[c - 'a'];
    }
    return ws.isWord;// if its not a word, also return false
  }
  
  
  /** Returns if there is any word in the trie that starts with the given prefix. */
  // in another word, if there is a prefix , this is similar to the above 
  public boolean startsWith(String prefix){
    TrieNode ws = root;
    for(int i = 0; i < prefix.length(); i++){
      char c = prefix.charAt(i);
      if(ws.children[c - 'a'] == null){
        return false;
      }
      ws = ws.children[c - 'a'];
    }
    return true;
  }
}
class TrieNode {
  public char val;
  public boolean isWord;
  public TrieNode[] children = new TrieNode[26];
  
  public TrieNode(char c){
    TrieNode node = new TrieNode();
    node.val = c;
  }
}
   

猜你喜欢

转载自www.cnblogs.com/tobeabetterpig/p/9450369.html
今日推荐