-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay5_WordDictionary.java
89 lines (66 loc) · 1.86 KB
/
Day5_WordDictionary.java
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
class WordDictionary {
WordDictionary[] children;
boolean isEndOfWord;
public WordDictionary() {
children = new WordDictionary[26];
isEndOfWord=false;
}
/** Adds a word into the data structure. */
public void addWord(String word) {
WordDictionary cur=this;
for(char c:word.toCharArray())
{
if(cur.children[c-'a']==null)
cur.children[c-'a'] = new WordDictionary();
cur=cur.children[c-'a'];
}
cur.isEndOfWord=true;
}
public boolean search(String word) {
WordDictionary cur= this;
for( int i=0;i<word.length();++i)
{
char c=word.charAt(i);
if(c=='.')
{
for(WordDictionary child:cur.children)
if(child!=null && child.search(word.substring(i+1))) return true;
return false;
}
if(cur.children[c-'a']==null)
return false;
cur=cur.children[c-'a'];
}
return (cur!=null && cur.isEndOfWord);
}
}
// regular Expression approach
class WordDictionary {
HashSet<String> list;
/** Initialize your data structure here. */
public WordDictionary1() {
this.list = new HashSet<String>();
}
/** Adds a word into the data structure. */
public void addWord(String word) {
if(!list.contains(word))
list.add(word);
}
/** 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) {
boolean flag=false;
if(this.list.contains(word))
flag=true;
else {
for(String i:list)
{
if(i.matches(word))
flag=true;
}
}
return flag;
}
}