Longest Repeating Substring in C++


Suppose we have a string S, we have to find the length of the longest repeating substring(s). We will return 0 if no repeating substring is present. So if the string is like “abbaba”, then the output will be 2. As the longest repeating substring is “ab” or “ba”.

Return all words that can be formed in this manner, in lexicographical order.

To solve this, we will follow these steps −

  • n := size of S

  • set S := one blank space concatenated with S

  • set ret := 0

  • create one matrix dp of size (n + 1) x (n + 1)

  • for i in range 1 to n

    • for j in range i + 1 to n

      • if S[i] = S[j]

        • dp[i, j] := max of dp[i, j] and 1 + dp[i – 1, j - 1]

        • ret := max of ret and dp[i, j]

  • return ret

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int longestRepeatingSubstring(string S) {
      int n = S.size();
      S = " " + S;
      int ret = 0;
      vector < vector <int> > dp(n + 1, vector <int> (n + 1));
      for(int i = 1; i <= n; i++){
         for(int j = i + 1; j <= n; j++){
            if(S[i] == S[j]){
               dp[i][j] = max(dp[i][j], 1 + dp[i - 1][j - 1]);
               ret = max(ret, dp[i][j]);
            }
         }
      }
      return ret;
   }
};
main(){
   Solution ob;
   cout << (ob.longestRepeatingSubstring("abbaba"));
}

Input

"abbaba"

Output

2

Updated on: 30-Apr-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements