标签:
Design a data structure that supports the following two operations: addWord(word)
andsearch(word)
search(word)
can search a literal word or a regular expression string containing only lettersa-z
or .
.
A .
means it can represent any one letter.
You may assume that all words are consist of lowercase letters a-z.
addWord("bad") addWord("dad") addWord("mad") search("pad") // return false search("bad") // return true search(".ad") // return true search("b..") // return true
分析:
使用Trie
1 public class WordDictionary { 2 3 private TrieNode root = new TrieNode(); 4 // Adds a word into the data structure. 5 6 public void addWord(String word) { 7 if (search(word) == true) return; 8 9 TrieNode current = root; 10 for (int i = 0; i < word.length(); i++) { 11 TrieNode child = current.subNode(word.charAt(i)); 12 if (child != null) { 13 current = child; 14 } else { 15 current.childList.add(new TrieNode(word.charAt(i))); 16 current = current.subNode(word.charAt(i)); 17 } 18 current.count++; 19 } 20 // Set isEnd to indicate end of the word 21 current.isEnd = true; 22 } 23 24 // Returns if the word is in the trie. 25 public boolean search(String word) { 26 for (TrieNode child : root.childList) { 27 if (search(child, word)) { 28 return true; 29 } 30 } 31 return false; 32 } 33 34 public boolean search(TrieNode current, String word) { 35 if (current == null) return false; 36 if (word.length() == 0) return true; 37 38 char c = word.charAt(0); 39 40 if (word.length() == 1) { 41 if (c == ‘.‘ && current.isEnd) 42 return true; 43 else if (current.content == c && current.isEnd) 44 return true; 45 else 46 return false; 47 } else { 48 if (c == ‘.‘) { 49 for (TrieNode child : current.childList) { 50 if (search(child, word.substring(1))) { 51 return true; 52 } 53 } 54 return false; 55 } else { 56 if (current.content == c) { 57 for (TrieNode child : current.childList) { 58 if (search(child, word.substring(1))) { 59 return true; 60 } 61 } 62 return false; 63 } else { 64 return false; 65 } 66 } 67 } 68 } 69 } 70 71 // Your WordDictionary object will be instantiated and called as such: 72 // WordDictionary wordDictionary = new WordDictionary(); 73 // wordDictionary.addWord("word"); 74 // wordDictionary.search("pattern"); 75 76 class TrieNode { 77 // Initialize your data structure here. 78 char content; // the character in the node 79 boolean isEnd; // whether the end of the words 80 int count; // the number of words sharing this character 81 LinkedList<TrieNode> childList; // the child list 82 83 public TrieNode() { 84 childList = new LinkedList<TrieNode>(); 85 content = ‘ ‘; 86 } 87 88 public TrieNode(char c) { 89 childList = new LinkedList<TrieNode>(); 90 content = c; 91 } 92 93 public TrieNode subNode(char c) { 94 for (TrieNode eachChild : childList) { 95 if (eachChild.content == c) { 96 return eachChild; 97 } 98 } 99 return null; 100 } 101 }
标签:
原文地址:http://www.cnblogs.com/beiyeqingteng/p/5665533.html