[LeetCode] Number of Distinct Substrings in a String

1698. Number of Distinct Substrings in a String

Given a string s, return the number of distinct substrings of s.

A substring of a string is obtained by deleting any number of characters (possibly zero) from the front of the string and any number (possibly zero) from the back of the string.

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
class Solution {
vector<int> sa, g, tg, lcp, rsa;
int t, n;
void suffixArray(string& s) {
t = 1, n = s.length();
sa = vector<int>(n);
tg = vector<int>(n + 1);
g = vector<int>(n + 1);

for(int i = 0; i < n; i++) {
sa[i] = i;
g[i] = s[i] - 'a';
}

while(t <= n) {
g[n] = -1;
auto compare = [g = g, t = t](int x, int y) {
if(g[x] == g[y])
return g[x + t] < g[y + t];
return g[x] < g[y];
};
sort(begin(sa), end(sa), compare);
tg[sa[0]] = 0;
for(int i = 1; i < n; i++)
tg[sa[i]] = tg[sa[i-1]] + compare(sa[i-1],sa[i]);
g = tg;
t<<=1;
}
}
void longestCommonPrefix(string& s) {
suffixArray(s);
lcp = vector<int>(n);
rsa = vector<int>(n);
for(int i = 0; i < n; i++)
rsa[sa[i]] = i;
int len = 0;
for(int i = 0; i < n; i++) {
int k = rsa[i];
if(k) {
int j = sa[k-1];
while(s[i+len] == s[j+len]) len++;
lcp[k] = len;
if(len) --len;
}
}
}
public:
int countDistinct(string s) {
longestCommonPrefix(s);
return n * (n + 1) / 2 - accumulate(begin(lcp),end(lcp),0);
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/03/PS/LeetCode/number-of-distinct-substrings-in-a-string/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.