-
Notifications
You must be signed in to change notification settings - Fork 360
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #623 from Vip2016-0/LeetCodeSol
Implement_Trie
- Loading branch information
Showing
1 changed file
with
55 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
class Node { | ||
public: | ||
char c; | ||
Node* child[26]; | ||
bool isWord; | ||
|
||
Node(char c) { | ||
this -> c = c; | ||
isWord = false; | ||
|
||
for(int i = 0 ; i < 26 ; i++) | ||
child[i] = NULL; | ||
} | ||
}; | ||
|
||
class Trie { | ||
Node* root; | ||
Node* getNode(string &s){ | ||
Node* curr = root; | ||
for(auto &ch:s){ | ||
if(curr -> child[ch - 97] == NULL) | ||
return NULL; | ||
curr = curr -> child[ch - 97]; | ||
} | ||
|
||
return curr; | ||
} | ||
public: | ||
Trie() { | ||
root = new Node('\0'); | ||
} | ||
|
||
void insert(string word) { | ||
Node* curr = root; | ||
|
||
for(auto &ch:word){ | ||
if(curr -> child[ch - 97] == NULL) | ||
curr -> child[ch - 97] = new Node(ch); | ||
curr = curr -> child[ch - 97]; | ||
} | ||
|
||
curr -> isWord = true; | ||
} | ||
|
||
bool search(string word) { | ||
Node* reqNode = getNode(word); | ||
|
||
return reqNode && reqNode -> isWord; | ||
} | ||
|
||
bool startsWith(string prefix) { | ||
return getNode(prefix) != NULL; | ||
} | ||
}; | ||
|