码迷,mamicode.com
首页 > 其他好文 > 详细

211 Add and Search Word - Data structure design

时间:2018-08-09 19:28:53      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:oid   check   word   let   rdd   add   ror   root   return   

211 Add and Search Word - Data structure design



??///Line 10: error: cannot find symbol: class WordDictionary



class WordDictionary {
  
  public class TrieNode{
    public TrieNode[] children = new TrieNode[26];
    public boolean isWord;/////
    
    private TrieNode root = new TrieNode();

    /** Initialize your data structure here. */
    public WordDictionary() {
        
    }
    
    /** Adds a word into the data structure. */
    public void addWord(String word) {
      TrieNode node = root;
      for(int i = 0; i < word.length(); i++){
        char c = word.charAt(i);
        if(node.children[c - ‘a‘] == null){
          node.children[c - ‘a‘] = new TrieNode(c);
        }
        node = node.children[c - ‘a‘];
      }
      node.isWord = 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 match(word.toCharArray(), 0, root);    
    }
    
    private boolean match(char[] chs, int k, TrieNode node){
      if(k == chs.length) return node.isWord;
      if(chs[k] != ‘.‘){
        // first check if it has a node chs[k]
        return node.children[chs[k] - ‘a‘] != null && match(chs, k+1, node.children[chs[k] - ‘a‘]);
      }else{
        // search all possibilities , if all full, then 26, so first check which one is full
        for(int i = 0; i < node.children.length; i++){
          if(node.children[i] != null){
            if(match(chs, k+1, node.children[i])){
              return true;
            }
          }
        }
      }
      return false;
    }
  }
}
  



////
    public boolean search(String word){
      return match(word.toCharArray(), 0, root);
    }

    private boolean match(char[] chs, int k, TrieNode node){
      if(k == chs.length) return node.isWord;
      if(chs[k] != ‘.‘){
        char current = chs[k];
        if(node.children[current - ‘a‘] != null){
          return match(chs, k+1, node.children[current - ‘a‘]);
        }
      }else{
        for(int i = 0; i < node.children.length; i++){
          if(node.children[i] != null){
            return match(chs, k+1, node.children[i]);
          }
        }
      }
      return false;
////

 

211 Add and Search Word - Data structure design

标签:oid   check   word   let   rdd   add   ror   root   return   

原文地址:https://www.cnblogs.com/tobeabetterpig/p/9450997.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!