|
| 1 | +package com.leosanqing.leetcode.medium.tree; |
| 2 | + |
| 3 | +/** |
| 4 | + * @Author: rtliu |
| 5 | + * @Date: 2020/6/28 下午3:58 |
| 6 | + * @Package: com.leosanqing.leetcode.medium.tree |
| 7 | + * @Description: Design a data structure that supports the following two operations: |
| 8 | + * void addWord(word) bool search(word) search(word) can search a literal word |
| 9 | + * or a regular expression string containing only letters a-z or .. A . means it can represent any one letter. |
| 10 | + * Example: |
| 11 | + * addWord("bad") |
| 12 | + * addWord("dad") |
| 13 | + * addWord("mad") |
| 14 | + * search("pad") -> false |
| 15 | + * search("bad") -> true |
| 16 | + * search(".ad") -> true |
| 17 | + * search("b..") -> true |
| 18 | + * @Version: 1.0 |
| 19 | + */ |
| 20 | +public class _211_addAndSearchWord_dataStructureDesign { |
| 21 | + |
| 22 | +} |
| 23 | + |
| 24 | +class WordDictionary { |
| 25 | + TrieNode1 root = new TrieNode1(); |
| 26 | + |
| 27 | + /** Initialize your data structure here. */ |
| 28 | + public WordDictionary() { |
| 29 | + |
| 30 | + } |
| 31 | + |
| 32 | + /** Adds a word into the data structure. */ |
| 33 | + public void addWord(String word) { |
| 34 | + TrieNode1 curr = root; |
| 35 | + if(word != null && word.length() > 0){ |
| 36 | + |
| 37 | + for (char c : word.toCharArray()) { |
| 38 | + if (curr.children[c - 'a'] == null) { |
| 39 | + curr.children[c - 'a'] = new TrieNode1(); |
| 40 | + } |
| 41 | + curr = curr.children[c -'a']; |
| 42 | + |
| 43 | + } |
| 44 | + curr.isEnd = true; |
| 45 | + |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + /** Returns if the word is in the data structure. |
| 50 | + * A word could contain the dot character '.' to represent any one letter. */ |
| 51 | + public boolean search(String word) { |
| 52 | + return helper(word, 0 , root); |
| 53 | + } |
| 54 | + |
| 55 | + |
| 56 | + private boolean helper(String word, int index, TrieNode1 curr){ |
| 57 | + if(index >= word.length()){ |
| 58 | + return curr.isEnd; |
| 59 | + } |
| 60 | + char c = word.charAt(index); |
| 61 | + |
| 62 | + if('.' == c){ |
| 63 | + for (int i = 0; i < curr.children.length; i++) { |
| 64 | + // 当出现 . 的时候,递归遍历 |
| 65 | + if(curr.children[i] != null && helper(word, index+1, curr.children[i])){ |
| 66 | + return true; |
| 67 | + } |
| 68 | + } |
| 69 | + return false; |
| 70 | + }else { |
| 71 | + return (curr.children[c - 'a'] != null) && helper(word,index +1, curr.children[c - 'a']); |
| 72 | + } |
| 73 | + } |
| 74 | +} |
| 75 | + |
| 76 | +class TrieNode1 { |
| 77 | + TrieNode1[] children = new TrieNode1[26]; |
| 78 | + |
| 79 | + boolean isEnd = false; |
| 80 | + |
| 81 | +} |
| 82 | + |
| 83 | + |
0 commit comments