Skip to content

Commit 4a1163a

Browse files
Added files
1 parent a0797b3 commit 4a1163a

File tree

2 files changed

+58
-3
lines changed

2 files changed

+58
-3
lines changed

30-days-of-code-may/11.singleElementInSortedArray.cpp

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,9 @@ class Solution {
22
public:
33
int singleNonDuplicate(vector<int>& nums) {
44

5-
int start = 0, end = nums.size() - 1, mid;
6-
5+
int start = 0, end = nums.size() - 1, mid;
76
while(start < end){
87
mid = start + (end - start) / 2;
9-
108
if(mid % 2 == 0){
119
if(nums[mid] == nums[mid+1]) start = mid + 2;
1210
else if(nums[mid] == nums[mid-1]) end = mid - 2;
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
class Trie {
2+
3+
private:
4+
Trie *next[26] = {};
5+
bool isWord = false;
6+
7+
8+
public:
9+
/** Initialize your data structure here. */
10+
Trie() {}
11+
12+
/** Inserts a word into the trie. */
13+
void insert(string word) {
14+
Trie *node = this;
15+
for(auto ch : word){
16+
ch -= 'a';
17+
18+
if(!node->next[ch]){
19+
node->next[ch] = new Trie();
20+
}
21+
node = node->next[ch];
22+
}
23+
node->isWord = true;
24+
}
25+
26+
/** Returns if the word is in the trie. */
27+
bool search(string word) {
28+
Trie *node = this;
29+
for(auto ch : word){
30+
ch -= 'a';
31+
32+
if(!node->next[ch]) return false;
33+
node = node->next[ch];
34+
}
35+
return node->isWord;
36+
}
37+
38+
/** Returns if there is any word in the trie that starts with the given prefix. */
39+
bool startsWith(string prefix) {
40+
41+
Trie *node = this;
42+
for(auto ch : prefix){
43+
ch -= 'a';
44+
if(!node->next[ch]) return false;
45+
node = node->next[ch];
46+
}
47+
return true;
48+
}
49+
};
50+
51+
/**
52+
* Your Trie object will be instantiated and called as such:
53+
* Trie* obj = new Trie();
54+
* obj->insert(word);
55+
* bool param_2 = obj->search(word);
56+
* bool param_3 = obj->startsWith(prefix);
57+
*/

0 commit comments

Comments
 (0)