-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
69 lines (52 loc) · 1.43 KB
/
main.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
class Solution {
struct Node {
array<Node *, 26> children;
Node() { children.fill(nullptr); }
~Node() {
for (auto &c : children) {
if (c) delete c;
}
}
};
public:
int countDistinct(string s) {
int n = s.size();
auto root = new Node();
int result = 0;
for (int i = 0; i < n; ++i) {
auto curr = root;
for (int j = i; j < n; ++j) {
char k = s[j] - 'a';
if (curr->children[k] == nullptr) {
curr->children[k] = new Node();
++result;
}
curr = curr->children[k];
}
}
delete root;
return result;
}
};
// https://leetcode.com/problems/number-of-distinct-substrings-in-a-string/solutions/985468/c-max-match-suffix-clean-code/
class Solution {
public:
int countDistinct(string s) {
int n = s.size();
vector<int> dp(n);
for (int d = 1; d < n; d++) {
int len = 0;
for (int l = 0; l < n; l++) {
int r = l + d;
if (r >= n) break;
s[l] == s[r] ? ++len : len = 0;
dp[r] = max(dp[r], len);
}
}
int result = 0;
for (int i = 0; i < n; i++) {
result += i + 1 - dp[i];
}
return result;
}
};