LeetCode211. 添加与搜索单词 - 数据结构设计(相关话题:Trie前缀树)
分析:把Trie当做字符串的集合来使用,添加单词,查询单词是否存在
1 import java.util.TreeMap; 2 class WordDictionary { 3 private class Node{ 4 public boolean isWord; 5 public TreeMap<Character, Node> next; 6 7 public Node(boolean isWord){ 8 this.isWord = isWord; 9 next = new TreeMap<>(); 10 } 11 12 public Node(){ 13 this(false); 14 } 15 } 16 private Node root; 17 18 /** Initialize your data structure here. */ 19 public WordDictionary() { 20 root = new Node(); 21 22 } 23 24 /** Adds a word into the data structure. */ 25 public void addWord(String word) { 26 Node cur = root; 27 for(int i = 0; i < word.length(); i++){ 28 char c = word.charAt(i); 29 if(cur.next.get(c) == null){ // 当前节点的next中是否存在字符c对应的下一个节点的映射 30 cur.next.put(c, new Node()); 31 } 32 cur = cur.next.get(c); 33 } 34 cur.isWord = true; 35 36 } 37 38 /** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */ 39 public boolean search(String word) { 40 return match(root, word, 0); 41 42 } 43 private boolean match(Node node, String word, int index){ 44 if(index == word.length()){ 45 return node.isWord; 46 } 47 char c = word.charAt(index); 48 if(c != '.'){ 49 if(node.next.get(c) == null){ 50 return false; 51 } 52 return match(node.next.get(c), word, index + 1); 53 } 54 // 等于'.'的情况是node的下一个字符的所有可能都去匹配 55 else{ 56 for(char nextChar : node.next.keySet()){ 57 if(match(node.next.get(nextChar), word, index + 1)){ 58 return true; 59 } 60 } 61 return false; 62 63 } 64 } 65 } 66 67 /** 68 * Your WordDictionary object will be instantiated and called as such: 69 * WordDictionary obj = new WordDictionary(); 70 * obj.addWord(word); 71 * boolean param_2 = obj.search(word); 72 */