forked from wisdompeak/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create 677.Map-Sum-Pairs-My-SubmissionsBack-to-Contest.cpp
- Loading branch information
1 parent
b964fa6
commit 4560e2a
Showing
1 changed file
with
65 additions
and
0 deletions.
There are no files selected for viewing
65 changes: 65 additions & 0 deletions
65
...m-Pairs-My-SubmissionsBack-to-Contest/677.Map-Sum-Pairs-My-SubmissionsBack-to-Contest.cpp
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,65 @@ | ||
class MapSum { | ||
class TrieNode | ||
{ | ||
public: | ||
TrieNode* next[26]; | ||
int val; | ||
TrieNode() | ||
{ | ||
for (int i=0; i<26; i++) | ||
next[i]=NULL; | ||
val=0; | ||
} | ||
}; | ||
TrieNode* root; | ||
public: | ||
/** Initialize your data structure here. */ | ||
MapSum() | ||
{ | ||
root=new TrieNode(); | ||
} | ||
|
||
void insert(string key, int val) | ||
{ | ||
TrieNode* node=root; | ||
for (int i=0; i<key.size(); i++) | ||
{ | ||
char ch=key[i]; | ||
if (node->next[ch-'a']==NULL) | ||
node->next[ch-'a']=new TrieNode(); | ||
node=node->next[ch-'a']; | ||
} | ||
node->val=val; | ||
} | ||
|
||
int sum(string prefix) | ||
{ | ||
TrieNode* node=root; | ||
for (int i=0; i<prefix.size(); i++) | ||
{ | ||
char ch=prefix[i]; | ||
if (node->next[ch-'a']==NULL) | ||
node->next[ch-'a']=new TrieNode(); | ||
node=node->next[ch-'a']; | ||
} | ||
int SUM=0; | ||
DFS(node,SUM); | ||
return SUM; | ||
} | ||
|
||
void DFS(TrieNode* node, int & SUM) | ||
{ | ||
if (node==NULL) return; | ||
|
||
SUM+=node->val; | ||
for (int i=0; i<26; i++) | ||
DFS(node->next[i],SUM); | ||
} | ||
}; | ||
|
||
/** | ||
* Your MapSum object will be instantiated and called as such: | ||
* MapSum obj = new MapSum(); | ||
* obj.insert(key,val); | ||
* int param_2 = obj.sum(prefix); | ||
*/ |