字典树搜索LINTCODE 题目Add and Search Word

本文详细介绍了如何使用Trie树实现一个高效、灵活的单词字典,包括添加单词、搜索单词等核心功能。
  1. public class WordDictionary {  
  2.     private TrieNode root = new TrieNode();  
  3.   
  4.     public void addWord(String word) {  
  5.         Map<Character, TrieNode> children = root.children;  
  6.         for(int i=0; i<word.length(); i++) {  
  7.             char c = word.charAt(i);  
  8.             TrieNode t;  
  9.             if(children.containsKey(c)) {  
  10.                 t = children.get(c);  
  11.             } else {  
  12.                 t = new TrieNode(c);  
  13.                 children.put(c, t);  
  14.             }  
  15.             children = t.children;  
  16.             if(i==word.length()-1) t.leaf=true;  
  17.         }  
  18.     }  
  19.   
  20.     public boolean search(String word) {  
  21.         return searchNode(word, root);  
  22.     }  
  23.       
  24.     public boolean searchNode(String word, TrieNode tn) {  
  25.         if(tn==null) return false;  
  26.         if(word.length() == 0 ) return tn.leaf;  
  27.           
  28.         Map<Character, TrieNode> children = tn.children;  
  29.         TrieNode t = null;  
  30.         char c = word.charAt(0);  
  31.         if(c=='.') {  
  32.             for(char key : children.keySet() ) {  
  33.                 if(searchNode(word.substring(1), children.get(key) )) return true;  
  34.             }  
  35.             return false;  
  36.         } else if(!children.containsKey(c)) {  
  37.             return false;  
  38.         } else {  
  39.             t = children.get(c);  
  40.             return searchNode(word.substring(1), t);  
  41.         }  
  42.     }      
  43. }  
  44.   
  45. class TrieNode {  
  46.     // Initialize your data structure here.  
  47.     char c;  
  48.     boolean leaf;  
  49.     HashMap<Character, TrieNode> children = new HashMap<Character, TrieNode>();  
  50.       
  51.     public TrieNode(char c) {  
  52.         this.c = c;  
  53.     }  
  54.           
  55.     public TrieNode(){};  
  56. }  

转载于:https://www.cnblogs.com/zhaoprence/p/4999403.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值