-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path211.cpp
More file actions
78 lines (69 loc) · 1.88 KB
/
211.cpp
File metadata and controls
78 lines (69 loc) · 1.88 KB
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
//
// 211.cpp
// LeetCode
//
// Created by 张佐玮 on 15/8/7.
// Copyright (c) 2015年 JarvisZhang. All rights reserved.
//
// Title: Add and Search Word - Data structure design
//
#include <iostream>
using namespace std;
class TrieNode {
public:
bool end;
TrieNode *child[26];
TrieNode() {
for (int i = 0; i < 26; i++) {
child[i] = NULL;
}
end = false;
}
};
class WordDictionary {
private:
TrieNode *root;
bool searchRecur(string &word, int pos, TrieNode *¤t) {
if (current == NULL) {
return false;
}
else if (pos == word.size()) {
return current -> end;
}
else if (word[pos] != '.') {
return searchRecur(word, pos + 1, current -> child[word[pos]-'a']);
}
else {
bool found = false;
for (int i = 0; i < 26 && !found; i++) {
found = searchRecur(word, pos + 1, current -> child[i]);
}
return found;
}
}
public:
WordDictionary() {
root = new TrieNode();
}
// Adds a word into the data structure.
void addWord(string word) {
TrieNode *current = root;
for (char ch: word) {
if (current -> child[ch-'a'] == NULL) {
TrieNode *temp = new TrieNode();
current -> child[ch-'a'] = temp;
}
current = current -> child[ch-'a'];
}
current -> end = true;
}
// Returns if the word is in the data structure. A word could
// contain the dot character '.' to represent any one letter.
bool search(string word) {
return searchRecur(word, 0, root);
}
};
// Your WordDictionary object will be instantiated and called as such:
// WordDictionary wordDictionary;
// wordDictionary.addWord("word");
// wordDictionary.search("pattern");