题目

Design a data structure that supports the following two operations:

  1. void addWord(word)
  2. 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:

  1. addWord("bad")
  2. addWord("dad")
  3. addWord("mad")
  4. search("pad") -> false
  5. search("bad") -> true
  6. search(".ad") -> true
  7. search("b..") -> true

Note:
You may assume that all words are consist of lowercase letters a-z.


题意

设计一个数据结构,支持插入单词和搜索单词两个操作。其中,搜索单词的参数可以是一个包含通配符”.”的正则。

思路

0208. Implement Trie (Prefix Tree) (M) 一样使用字典树。不同之处在于当搜索字符为”.”时,要查找所有出现过的字母。


代码实现

Java

  1. class WordDictionary {
  2. Node root;
  3. /** Initialize your data structure here. */
  4. public WordDictionary() {
  5. root = new Node();
  6. }
  7. /** Adds a word into the data structure. */
  8. public void addWord(String word) {
  9. Node p = root;
  10. for (char c : word.toCharArray()) {
  11. if (p.children[c - 'a'] == null) {
  12. p.children[c - 'a'] = new Node();
  13. }
  14. p = p.children[c - 'a'];
  15. }
  16. p.end = true;
  17. }
  18. /**
  19. * Returns if the word is in the data structure. A word could contain the dot
  20. * character '.' to represent any one letter.
  21. */
  22. public boolean search(String word) {
  23. return search(word, 0, root);
  24. }
  25. private boolean search(String word, int index, Node p) {
  26. if (index == word.length()) {
  27. return p.end;
  28. }
  29. char c = word.charAt(index);
  30. if (c == '.') {
  31. for (Node next : p.children) {
  32. if (next != null && search(word, index + 1, next)) {
  33. return true;
  34. }
  35. }
  36. return false;
  37. } else {
  38. return p.children[c - 'a'] != null ? search(word, index + 1, p.children[c - 'a']) : false;
  39. }
  40. }
  41. }
  42. class Node {
  43. Node[] children = new Node[26];
  44. boolean end;
  45. }
  46. /**
  47. * Your WordDictionary object will be instantiated and called as such:
  48. * WordDictionary obj = new WordDictionary(); obj.addWord(word); boolean param_2
  49. * = obj.search(word);
  50. */