hello guys i was given homework problem where it asks me to find all distinct substring of a string. I have implemented a method which will tell you all the substrings of s
This algorithm uses just the Z-function / Z algorithm.
For each prefix i of the word, reverse it and do z_function over it.
The number of new distinct substrings that end in i
is (the length of the prefix) — (maximum value in the z_function array)
.
The pseudo code looks like this:
string s; cin >> s;
int sol = 0
foreach i to s.size()-1
string x = s.substr( 0 , i+1 );
reverse( x.begin() , x.end() );
vector z = z_function( x );
//this works too
//vector z = prefix_functionx(x);
int mx = 0;
foreach j to x.size()-1
mx = max( mx , z[j] );
sol += (i+1) - mx;
cout << sol;
The time complexity of this algorithm is O(n^2). The maximum can be returned from the z_function as well.
Source.
This is not my original answer. I am merely linking to it and pasting it in case the link goes down.