Add and Search Word
Posted keepshuatishuati
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Add and Search Word相关的知识,希望对你有一定的参考价值。
1 public class WordDictionary { 2 public class TrieNode { 3 TrieNode[] children = new TrieNode[26]; 4 boolean isWord; 5 TrieNode(){} 6 } 7 8 private TrieNode root; 9 10 public WordDictionary() { 11 root = new TrieNode(); 12 } 13 // Adds a word into the data structure. 14 public void addWord(String word) { 15 TrieNode current = root; 16 for (int i = 0; i < word.length(); i++) { 17 if (current.children[word.charAt(i) - ‘a‘] == null) { 18 current.children[word.charAt(i) - ‘a‘] = new TrieNode(); 19 } 20 current = current.children[word.charAt(i) - ‘a‘]; 21 } 22 current.isWord = true; 23 } 24 25 // Returns if the word is in the data structure. A word could 26 // contain the dot character ‘.‘ to represent any one letter. 27 public boolean search(String word) { 28 TrieNode current = root; 29 return search(word.toCharArray(), 0, root); 30 } 31 32 private boolean search(char[] letters, int index, TrieNode root) { 33 if (index == letters.length) { 34 return root.isWord; 35 } 36 if (letters[index] != ‘.‘) { 37 return root.children[letters[index] - ‘a‘] != null && search(letters, index + 1, root.children[letters[index] - ‘a‘]); 38 } else { 39 for (int i = 0; i < 26; i++) { 40 if (root.children[i] != null && search(letters, index + 1, root.children[i])) { 41 return true; 42 } 43 } 44 } 45 return false; 46 } 47 } 48 49 // Your WordDictionary object will be instantiated and called as such: 50 // WordDictionary wordDictionary = new WordDictionary(); 51 // wordDictionary.addWord("word"); 52 // wordDictionary.search("pattern");
1. check children is null or not.
以上是关于Add and Search Word的主要内容,如果未能解决你的问题,请参考以下文章
[LintCode] Add and Search Word 添加和查找单词
211. Add and Search Word - Data structure design
211. Add and Search Word - Data structure design