1 class WordDictionary { 2 //使用什么来存储单词 ------>字典树?? 3 4 //字典树 5 // 1 新建节点 6 static class TireNode{ 7 boolean flag ; //记录该单词是否出现 8 Map<Character, TireNode> childNode; 9 10 public TireNode() 11 { 12 flag = false; 13 childNode = new HashMap<Character, TireNode>(); 14 } 15 } 16 TireNode node; 17 18 /** Initialize your data structure here. */ 19 public WordDictionary() { 20 node = new TireNode(); //新建根节点,不存储任何字符 21 } 22 23 /** Adds a word into the data structure. */ 24 //添加一个单词 25 public void addWord(String word) { 26 char[] letter = word.toCharArray(); 27 TireNode curnode = node; 28 for(int i = 0 ; i < letter.length ; i++) 29 { 30 char cur = letter[i]; 31 //从根节点寻找 32 if(!curnode.childNode.containsKey(cur)) //子节点不存在就添加 33 { 34 curnode.childNode.put(cur,new TireNode()); 35 } 36 curnode = curnode.childNode.get(cur); 37 } 38 curnode.flag = true; 39 40 } 41 42 /** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */ 43 public boolean search(String word) { 44 TireNode root = node; 45 return backstack(root,word,0); 46 47 48 } 49 50 private boolean backstack(TireNode root , String str, int index) 51 { 52 if(index == str.length())return root.flag; 53 char i = str.charAt(index); 54 if(i == '.') 55 { 56 //遍历当前节点下的所有子节点 57 for(Map.Entry<Character, TireNode> entry : root.childNode.entrySet()){ 58 if(entry.getKey() != null && backstack(entry.getValue(),str,index+1)) 59 { 60 //存在一个就返回true 61 return true; 62 } 63 } 64 return false; 65 } 66 else 67 { 68 if(!root.childNode.containsKey(i)) 69 { 70 return false; 71 } 72 //直接进入下一个节点 73 return backstack(root.childNode.get(i),str , index+1); 74 75 } 76 77 78 } 79 }