Sum of similarities of string with all of its suffixes in C++


In this problem, we are given string str. Our task is to create a program to find the sum of similarities of the string with all of its suffixes.

Suffixes of string str are all the strings that are created by eliminating starting characters of the string.

Similarities of string str1 and str2 is the length of the longest prefix common to both the string. For example, str1 = ‘abbac’ and str2 = ‘abb’ is 3.

While str1 = ‘abca’ and str2 = ‘ca’ is 0. As we count from start.

Let’s take an example to understand the problem,

Input − str = ‘xyxyx’

Output

Explanation − All substrings and similarities of the string with all suffix are −

‘xyxyx’ -> 5
‘yxyx’ -> 0
‘xyx’ -> 3
‘yx’ -> 0
‘x’ -> 1
Sum = 5 + 0 + 3 + 0 + 1 = 9

To solve this problem, we will use Z-algorithm and calculate Z-array. Z-array is an array of length equal to the length of the string. Every element store a prefix of str. The below program shows the implementation,

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void createZArray(string str, int n, int Zarray[]) {
   int L, R, k;
   L = R = 0;
   for (int i = 1; i < n; ++i) {
      if (i > R) {
         L = R = i;
         while (R < n && str[R - L] == str[R])
            R++;
         Zarray[i] = R - L;
         R--;
      }
      else {
         k = i - L;
         if (Zarray[k] < R - i + 1)
         Zarray[i] = Zarray[k];
         else {
            L = i;
            while (R < n && str[R - L] == str[R])
            R++;
            Zarray[i] = R - L;
            R--;
         }
      }
   }
}
int calSumSimilarities(string s, int n) {
   int Zarray[n] = { 0 };
   createZArray(s, n, Zarray);
   int total = n;
   for (int i = 1; i < n; i++)
      total += Zarray[i];
   return total;
}
int main() {
   string s = "xyxyx";
   int n = s.length();
   cout<<"Sum of similarities of string with all of its suffixes is "<<calSumSimilarities(s, n);
   return 0;
}

Output

Sum of similarities of string with all of its suffixes is 9

Updated on: 05-Aug-2020

140 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements