就是trie
1 public class WordDictionary { 2 public class TrieNode { 3 public TrieNode[] child; 4 public char curChar; 5 public boolean isLeaf; 6 7 public TrieNode() { 8 child = new TrieNode[26]; 9 isLeaf = false; 10 } 11 } 12 13 TrieNode root; 14 15 public WordDictionary() { 16 root = new TrieNode(); 17 } 18 19 // Adds a word into the data structure. 20 public void addWord(String word) { 21 if(word.length() == 0) { 22 return; 23 } 24 TrieNode curNode = root; 25 for(int i = 0; i < word.length(); i++) { 26 char cur = word.charAt(i); 27 int index = cur - ‘a‘; 28 if(curNode.child[index] == null) { 29 curNode.child[index] = new TrieNode(); 30 curNode.child[index].curChar = cur; 31 } 32 curNode = curNode.child[index]; 33 } 34 curNode.isLeaf = true; 35 } 36 37 // Returns if the word is in the data structure. A word could 38 // contain the dot character ‘.‘ to represent any one letter. 39 public boolean search(String word) { 40 if(word.length() == 0) { 41 return true; 42 } 43 return searchHelper(word, root); 44 } 45 46 private boolean searchHelper(String word, TrieNode curNode) { 47 if(word.length() == 0) { 48 return curNode.isLeaf; 49 } 50 char cur = word.charAt(0); 51 String sub = word.substring(1); 52 if(cur != ‘.‘) { 53 int index = cur - ‘a‘; 54 if(curNode.child[index] == null) { 55 return false; 56 } 57 if(curNode.child[index].curChar != cur) { 58 return false; 59 } 60 return searchHelper(sub, curNode.child[index]); 61 } else { 62 for(int i = 0; i < 26; i++) { 63 if(curNode.child[i] != null && searchHelper(sub, curNode.child[i])) { 64 return true; 65 } 66 } 67 } 68 return false; 69 } 70 }
68行那里要return false因为在62行处,可能没有结果,开始写成true死都调不出来
时间: 2024-08-08 22:07:41