-
Notifications
You must be signed in to change notification settings - Fork 5
/
BS_DistinctSubstrings.cpp
147 lines (121 loc) · 2.92 KB
/
BS_DistinctSubstrings.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
/*
https://practice.geeksforgeeks.org/problems/count-of-distinct-substrings/1
https://binarysearch.com/problems/Distinct-Substrings
*/
// GFG ---------------------------------------------------
// { Driver Code Starts
#include<bits/stdc++.h>
using namespace std;
int countDistinctSubstring(string s);
int main()
{
int t,l,i,j;
int temp;
cin>>t;
while(t--){
string s;
cin>>s;
cout<<countDistinctSubstring(s)<<endl;
}
}
// } Driver Code Ends
class TrieNode{
public:
TrieNode* child[26] = {nullptr};
bool isEnd = false;
};
/*You are required to complete this method */
int countDistinctSubstring(string s)
{
TrieNode *root = new TrieNode;
int indx=0;
int ans=1; // for null
for(int i=0; i<s.length(); i++)
{
TrieNode *curr = root;
for(int j=i; j<s.length(); j++)
{
indx = s[j]-'a';
if(curr->child[indx] == nullptr)
curr->child[indx] = new TrieNode;
curr = curr->child[indx];
if(curr->isEnd == false)
{
ans++;
curr->isEnd = true;
}
}
}
return ans;
/* TLE in 4th Test Case
unordered_set<string> ans;
for(int i=0; i<s.length(); i++)
{
for(int j=i; j<s.length(); j++)
ans.insert(s.substr(i,j-i+1));
}
return ans.size()+1;
*/
/* TLE in 20th test case
unordered_set<unsigned long> ans;
for(int i=0; i<s.length(); i++)
{
unsigned long hash = 5381;
for(int j=i; j<s.length(); j++)
{
hash = ((hash<<5) + hash) + s[j] - 'a';
ans.insert(hash);
}
}
return ans.size()+1;
*/
}
// Binary Search ------------------------------------------------
int solve_1(string s) {
unordered_set<string> ans;
for(int i=0; i<s.length(); i++)
{
for(int j=i; j<s.length(); j++)
ans.insert(s.substr(i,j-i+1));
}
return ans.size();
}
int solve_2(string s) {
unordered_set<unsigned long> ans;
for(int i=0; i<s.length(); i++)
{
unsigned long hash = 5381;
for(int j=i; j<s.length(); j++)
{
hash = ((hash<<5) + hash) + s[j] - 'a';
ans.insert(hash);
}
}
return ans.size();
}
class TrieNode{
public:
TrieNode* child[26] = {nullptr};
bool isEnd = false;
};
int solve(string s) {
TrieNode* root = new TrieNode;
int ans=0, indx=0;
for(int i=0; i<s.size(); i++)
{
TrieNode* curr = root;
for(int j=i; j<s.size(); j++)
{
indx = s[j]-'a';
if(curr->child[indx] == nullptr)
curr->child[indx] = new TrieNode;
curr= curr->child[indx];
if(curr->isEnd == false)
{
ans++;
curr->isEnd = true;
}
}
}
return ans;
}