Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit84e015e

Browse files
authored
Merge pull requestneetcode-gh#86 from Pegasus02K/patch-10
Create 211-Design-Add-and-Search-Words-Data-Structure.cpp
2 parentsd0a57fa +230c4dd commit84e015e

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
structTrieNode {
2+
TrieNode* children[26];
3+
bool isWordEnd;
4+
5+
TrieNode() : isWordEnd(false) {
6+
for (int i =0; i <26; ++i)
7+
children[i] =nullptr;
8+
}
9+
};
10+
11+
classWordDictionary {
12+
private:
13+
TrieNode* root;
14+
public:
15+
WordDictionary() {
16+
root =new TrieNode;
17+
}
18+
19+
voidaddWord(string word) {
20+
// simple trie insertion
21+
TrieNode* cur = root;
22+
23+
int idx;
24+
for (int i =0; i < word.size(); ++i) {
25+
idx = word[i] -'a';
26+
if (cur->children[idx] ==nullptr)
27+
cur->children[idx] =new TrieNode;
28+
cur = cur->children[idx];
29+
}
30+
// mark the last node as end of a word
31+
cur->isWordEnd =true;
32+
}
33+
34+
boolrecursiveSearch(const string &word,int curIdx,const TrieNode *node) {
35+
auto cur = node;
36+
37+
for (int i = curIdx; i < word.size(); ++i) {
38+
if (word[i] =='.') {
39+
// can match any character - backtracking is required
40+
for (int j =0; j <26; ++j) {
41+
if (cur->children[j] ==nullptr)// skip non-existing characters
42+
continue;
43+
if (recursiveSearch(word, i +1, cur->children[j]))// try and backtrack if fails
44+
returntrue;
45+
}
46+
// search with backtracking failed in all children
47+
returnfalse;
48+
}
49+
else {
50+
// simple trie search
51+
int idx = word[i] -'a';
52+
if (cur->children[idx] ==nullptr)
53+
returnfalse;
54+
cur = cur->children[idx];
55+
}
56+
}
57+
// check if the node is end of any word
58+
return cur->isWordEnd;
59+
}
60+
61+
boolsearch(string word) {
62+
returnrecursiveSearch(word,0, root);
63+
}
64+
};

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp