Suffix tree to generate all substrings

22 Oct 2017
Suffix tree is a tree data structure that allows you to generate all substrings of a given string in linear time o(n). 
When compared to other algorithms, this uses less space and generates substrings in linear time. It also overlaps the repeating pattern, so it can result in data compression. 
Program to generate all substrings
#include <bits/stdc++.h>
using namespace std;

int main()
{
    char s[1000001], sb[1000001];
    cin >> s;
    int len = strlen(s);
    for (int i = 0; i < len; i++)
    {
        sb[0] = '\0';
        for (int j = i, idx = 0; j < len; j++, idx++)
        {
            sb[idx] = s[j];
            sb[idx + 1] = '\0';
            cout << sb << endl;
        }
    }
    return 0;
}
Trie helps us to save all substrings in a compressed fashion, and it helps to find count of distinct substrings formed by a string and also allows us to count the frequency of each substrings while forming the tree.
#include <bits/stdc++.h>
using namespace std;

struct Node
{
  public:
    bool IsEnd;
    struct Node *Alp[26];

    ~Node()
    {
        for (int i = 0; i < 26; i++)
            if (Alp[i] != NULL)
                delete Alp[i];
    }
};

int main()
{
    char s[1000001], sb[1000001];
    cin >> s;
    int len = strlen(s);
    struct Node *trie = new Node();
    for (int i = 0; i < len; i++)
    {
        struct Node *curtrie = trie;
        sb[0] = '\0';
        for (int j = i, idx = 0, cIdx; j < len; j++, idx++)
        {
            cIdx = s[j] - 'a';
            curtrie = curtrie->Alp[cIdx];

            if (curtrie == NULL)
            {
                curtrie = new Node();
                curtrie->Alp[cIdx] = curtrie;
            }
            sb[idx] = s[j];
            sb[idx + 1] = '\0';
            cout << sb << endl;
        }
    }
    delete trie;
    return 0;
}