
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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
#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
- Related Articles
- Longest Substring Without Repeating Characters in Python
- Longest Substring with At Least K Repeating Characters in C++
- Finding the longest Substring with At Least n Repeating Characters in JavaScript
- Program to find length of longest repeating substring in a string in Python
- Longest Repeating Character Replacement in C++
- Longest Palindromic Substring
- Longest Palindromic Substring in Python
- Longest Duplicate Substring in C++
- How to find the length of the longest substring from the given string without repeating the characters using C#?
- SequenceMatcher in Python for Longest Common Substring.
- Swap For Longest Repeated Character Substring in C++
- Program to find longest awesome substring in Python
- Finding the longest substring uncommon in array in JavaScript
- Program to find maximum k-repeating substring from sequence in Python
- Find longest consecutive letter and digit substring in Python

Advertisements