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;
////

猜你喜欢

转载自www.cnblogs.com/tobeabetterpig/p/9450997.html