Contents
  1. 1. 题目
  2. 2. 思路

题目

设计一个支持以下两种操作的数据结构:
void addWord(word)
bool search(word)
search(word) 可以搜索文字或正则表达式字符串,字符串只包含字母 . 或 a-z 。 . 可以表示任何一个字母。
示例:
addWord(“bad”)
addWord(“dad”)
addWord(“mad”)
search(“pad”) -> false
search(“bad”) -> true
search(“.ad”) -> true
search(“b..”) -> true
说明:
你可以假设所有单词都是由小写字母 a-z 组成的。

思路

用字典树可以解决,关键问题是.如何解决
我第一时间想到递归,遇到。要遍历整个子字符数组,
有一个递归标志符,表示已经匹配,这个标志符成功则返回,写的很乱,自己都懵逼
如何是. 就深度遍历,如果不是就匹配
结束条件,不匹配或到结尾,最后匹配是不是有结束符号
分两个2情况,一种是。,深度遍历,一种是具体值,走字典树
递归结束时index到数组结尾,返回结束标示符,需要空数组也返回false

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
class WordDictionary {
private TreeNode root;
public static class TreeNode{
private char data;
private TreeNode[] child = new TreeNode[26];
private boolean isEndingChar = false;
public TreeNode(char data){
this.data = data;
}
}
/** Initialize your data structure here. */
public WordDictionary() {
root = new TreeNode('/');
}

/** Adds a word into the data structure. */
public void addWord(String word) {
TreeNode node = root;
char[] array = word.toCharArray();
for(int i = 0 ;i < array.length ; i++){
int index = array[i] - 'a';
if(node.child[index] == null){
node.child[index] = new TreeNode(array[i]);
}
node = node.child[index];
}
node.isEndingChar = true;
}

/** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */
public boolean search(String word) {
if(word == null || word.length() == 0){
return true;
}
TreeNode node = root;
char[] array = word.toCharArray();
return helper(array,0,node);
}
public boolean helper(char[] array,int index,TreeNode node){
if(index == array.length){
return node.isEndingChar;
}
char data = array[index];

if(data == '.'){
TreeNode[] child = node.child;
for(int i = 0 ; i< child.length ; i++){

if(child[i] != null && helper(array, index+1, child[i])){
return true;
}
}
return false;
}else{
int num = data - 'a';
if(node.child[num] == null){
return false;
}
return helper(array,index+1, node.child[num]);
}

}
}

/**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary obj = new WordDictionary();
* obj.addWord(word);
* boolean param_2 = obj.search(word);
*/
Contents
  1. 1. 题目
  2. 2. 思路