Design a data structure that supports the following two operations:
void addWord(word) bool search(word)
search(word) can search a literal word or a regular expression string containing only letters a-z
or .
. A .
means it can represent any one letter.
Example:
addWord("bad") addWord("dad") addWord("mad") search("pad") -> false search("bad") -> true search(".ad") -> true search("b..") -> true
Note:
You may assume that all words are consist of lowercase letters
1 class WordDictionary { 2 private TrieNode root; 3 4 /** Initialize your data structure here. */ 5 public WordDictionary() { 6 root = new TrieNode(); 7 } 8 9 /** Adds a word into the data structure. */ 10 public void addWord(String word) { 11 TrieNode cur = root; 12 for (char c: word.toCharArray()) { 13 if (cur.children[c - ‘a‘] == null) { 14 cur.children[c - ‘a‘] = new TrieNode(); 15 } 16 cur = cur.children[c - ‘a‘]; 17 } 18 cur.isWord = true; 19 } 20 21 /** Returns if the word is in the data structure. A word could contain the dot character ‘.‘ to represent any one letter. */ 22 public boolean search(String word) { 23 return helper(word, root, 0); 24 } 25 26 private boolean helper(String word, TrieNode root, int level) { 27 if (level == word.length()) { 28 return root.isWord; 29 } 30 char cur = word.charAt(level); 31 if (cur == ‘.‘) { 32 for (TrieNode child : root.children) { 33 if (child != null && helper(word, child, level + 1)) { 34 return true; 35 } 36 } 37 return false; 38 } else { 39 return root.children[cur - ‘a‘] != null && helper(word, root.children[cur - ‘a‘], level + 1); 40 } 41 } 42 } 43 44 class TrieNode { 45 TrieNode[] children; 46 boolean isWord; 47 48 public TrieNode() { 49 children = new TrieNode[26]; 50 isWord = false; 51 } 52 } 53 54 /** 55 * Your WordDictionary object will be instantiated and called as such: 56 * WordDictionary obj = new WordDictionary(); 57 * obj.addWord(word); 58 * boolean param_2 = obj.search(word); 59 */
原文地址:https://www.cnblogs.com/xuanlu/p/12005192.html
时间: 2024-10-03 10:02:56