finding all distinct substring of a string

前端 未结 6 1771
借酒劲吻你
借酒劲吻你 2021-01-14 21:41

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

6条回答
  •  日久生厌
    2021-01-14 22:08

    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.

提交回复
热议问题