Tuesday, 26 Oct 2021

# Length of all prefixes that are also the suffixes of given string

Length of all prefixes that are also the suffixes of given string Given a string S consisting of N characters, the task is to find the length of all prefixes of the given string S that are also suffixes of the same string S.Examples:Input: S = “ababababab”Output: 2 4 6 8Explanation: The prefixes of S that are also its suffixes are:“ab” of length = 2“abab” of length = 4“ababab” of length = 6“abababab” of length = 8Input: S = “geeksforgeeks”Output: 5Naive Approach: The simplest approach to solve the given problem is to traverse the given string, S from the start, and in each iteration add the current character to the prefix string, and check if the prefix string is the same as the suffix of the same length or not. If found to be true, then print the length of the prefix string. Otherwise, check for the next prefix.Below is the implementation of the above approach:C++14  #include using namespace std;  void countSamePrefixSuffix(string s, int n){        string prefix = “”;          for (int i = 0; i < n - 1; i++) {                          prefix += s[i];                  string suffix = s.substr(            n - 1 - i, n - 1);                          if (prefix == suffix) {            cout