
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
#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
- Related Questions & Answers
- Trie of all Suffixes
- Program to find total similarities of a string and its substrings in Python
- Find sum of sum of all sub-sequences in C++
- Sum of XOR of all subarrays in C++
- Sum of XOR of sum of all pairs in an array in C++
- Sum of XOR of all possible subsets in C++
- Sum of the products of all possible Subsets in C++
- Sum of XOR of all pairs in an array in C++
- Sum of list (with string types) in Python
- How to check whether a string ends with one from a list of suffixes in Python?
- Print all possible sums of consecutive numbers with sum N in C++
- Find largest sum of digits in all divisors of n in C++
- Program to find out the similarity between a string and its suffixes in python
- Lowercase suffixes in C#
- Sum of all multiples in JavaScript