Repeated Substring Pattern in C++


Suppose we have a non-empty string. We have to check whether it can be constructed by taking a substring of it and appending multiple times of the substring. The string consists of lowercase English letters only and its length will not exceed 10000. So if the input is like “abaabaaba”, then answer will be true, as this is created using “aba”

To solve this, we will follow these steps −

  • We will use the dynamic programming approach.
  • Define an array DP of size n. n is the size of the string
  • i := 1 and j := 0
  • while i < n
    • if str[i] == str[j], then DP[i] := j + 1, increase i and j by 1
    • otherwise
      • if j > 0, then j := DP[j – 1]
      • else dp[i] := 0, and increase i by 1
  • if DP[n – 1] is not 0 and n % (n – DP[n – 1]) == 0
    • return true
  • otherwise return false

Example

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   void printVector(vector <int> v){
      for(int i = 0; i < v.size(); i++)cout << v[i] << " ";
      cout << endl;
   }
   bool repeatedSubstringPattern(string s) {
      int n = s.size();
      vector <int> dp(n);
      int i = 1;
      int j = 0;
      while(i < n){
         if(s[i] == s[j]){
            dp[i] = j+1;
            i++;
            j++;
         } else {
            if(j > 0){
               j = dp[j-1];
            } else {
               dp[i] = 0;
               i++;
            }
         }
      }
      return dp[n - 1] && n % (n - dp[n-1]) == 0;
   }
};
main(){
   Solution ob;
   string res = (ob.repeatedSubstringPattern("abaabaaba"))? "true" : "fasle";
   cout << res;
}

Input

"abaabaaba"

Output

true

Updated on: 28-Apr-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements