211 Add and Search Word - Data structure design

Posted tobeabetterpig

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了211 Add and Search Word - Data structure design相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

211. Add and Search Word - Data structure design

211. Add and Search Word - Data structure design

211. Add and Search Word - Data structure design

211. Add and Search Word - Data structure design

211. Add and Search Word - Data structure design

211. Add and Search Word - Data structure design