-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path078_Number Of Distinct Substring.cpp
77 lines (58 loc) · 1.3 KB
/
078_Number Of Distinct Substring.cpp
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
// Time Complexity -> O(n^3)
// Space Complexity -> O(n^2)
#include <bits/stdc++.h>
int distinctSubstring(string &word) {
// Write your code here.
int n = word.size();
set<string> st;
for(int i = 0; i < n; ++i)
{
string cur = "";
for(int j = i; j < n; ++j)
{
cur += word[j];
st.insert(cur);
}
}
return st.size();
}
#include <bits/stdc++.h>
class Node{
private:
Node* child[26] = {nullptr};
public:
bool containsKey(char ch)
{
return child[ch - 'a'] != nullptr;
}
void put(char ch, Node* node)
{
child[ch - 'a'] = node;
}
Node* get(char ch)
{
return child[ch - 'a'];
}
};
// Time Complexity -> O(n^2)
// Space Complexity -> O(n^2)
int distinctSubstring(string &word) {
// Write your code here.
int n = word.size();
Node* root = new Node();
int cnt = 0;
for(int i = 0; i < n; ++i)
{
Node *temp = root;
for(int j = i; j < n; ++j)
{
if(!temp->containsKey(word[j]))
{
++cnt;
temp->put(word[j], new Node());
}
temp = temp->get(word[j]);
}
}
return cnt;
}