Add and Search Word - Data structure design

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 ..

. means it can represent any one letter.

 Notice

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

Example
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     private TrieNode root = new TrieNode(' ');
 3     public void addWord(String word) {
 4         TrieNode current = root;
 5         for (int i = 0; i < word.length(); i++) {
 6             char ch = word.charAt(i);
 7             TrieNode node = current.getChildNode(ch);
 8             if (node == null) {
 9                 current.map.put(ch, new TrieNode(ch));
10                 node = current.getChildNode(ch);
11             }
12             current = node;
13         }
14         current.isEnd = true;
15     }
16 
17     // Returns if the word is in the trie.
18     public boolean search(String word) {
19         return helper(root, word, 0);
20     }
21 
22     public boolean helper(TrieNode current, String word, int index) {
23         if (current == null) return false;
24         if (index == word.length()) return current.isEnd;
25         char c = word.charAt(index);
26         if (c == '.') {
27             for (TrieNode child : current.map.values()) {
28                 if (helper(child, word, index + 1)) return true;
29             }
30         } else {
31             return helper(current.getChildNode(word.charAt(index)), word, index + 1);
32         }
33         return false;
34     }
35 }
36 
37 class TrieNode {
38     char ch;
39     boolean isEnd;
40     Map<Character, TrieNode> map;
41 
42     public TrieNode(char ch) {
43         this.ch = ch;
44         map = new HashMap<>();
45     }
46 
47     public TrieNode getChildNode(char ch) {
48         return map.get(ch);
49     }
50 }

 

转载于:https://www.cnblogs.com/beiyeqingteng/p/5665533.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值