-
Notifications
You must be signed in to change notification settings - Fork 0
/
wordsDataStructure.txt
90 lines (84 loc) · 2.1 KB
/
wordsDataStructure.txt
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
89
90
1211. Design Add and Search Words Data Structure
Design a data structure that supports adding new words and finding if a string matches any previously added string.
Implement the WordDictionary class:
WordDictionary() Initializes the object.
void addWord(word) Adds word to the data structure, it can be matched later.
bool search(word) Returns true if there is any string in the data structure that matches word or false otherwise.
word may contain dots '.' where dots can be matched with any letter.
struct Node{
Node* links[26];
bool flag;
public:
bool containsKey(char ch)
{
return links[ch-'a']!=NULL;
}
void put(char ch,Node* node)
{
links[ch-'a']=node;
}
Node* get(char ch)
{
return links[ch-'a'];
}
bool isEnd()
{
return flag;
}
void setEnd()
{
flag=true;
}
};
class WordDictionary
{
Node* root;
public:
WordDictionary()
{
root=new Node();
}
void addWord(string word)
{
Node* node=root;
for(int i=0;i<word.size();i++)
{
if(!node->containsKey(word[i]))
{
node->put(word[i],new Node());
}
node=node->get(word[i]);
}
node->setEnd();
}
bool helper(Node* root,string word,int index)
{
if(index==word.size() && root->isEnd()==true)
return true;
if(index==word.size() && root->isEnd()==false)
return false;
if(word[index]=='.')
{
for(int i=0;i<26;i++)
{
bool a;
if(root->links[i]!=NULL)
a=helper(root->links[i],word,index+1);
if(a==true)
return true;
}
return false;
}
else
{
if(root->links[word[index]-'a']==NULL)
return false;
return helper(root->links[word[index]-'a'],word,index+1);
}
}
bool search(string word)
{
Node* node=root;
return helper(node,word,0);
}
};