Longest Repeating Substring
This program finds longest repeating substring using DP.
Problem Statement
Write a Java program to find longest repeating substring in "banana".
Source Code
| 1 | public class LongestRepeatingSubstring { |
| 2 | public static void main(String[] args) { |
| 3 | System.out.println("Eduinq Longest Repeating Substring"); |
| 4 | String str="banana"; |
| 5 | int n=str.length(); |
| 6 | int[][] dp=new int[n+1][n+1]; |
| 7 | int maxLen=0, endIndex=0; |
| 8 | for(int i=1;i<=n;i++){ |
| 9 | for(int j=i+1;j<=n;j++){ |
| 10 | if(str.charAt(i-1)==str.charAt(j-1)){ |
| 11 | dp[i][j]=dp[i-1][j-1]+1; |
| 12 | if(dp[i][j]>maxLen){ |
| 13 | maxLen=dp[i][j]; |
| 14 | endIndex=i; |
| 15 | } |
| 16 | } |
| 17 | } |
| 18 | } |
| 19 | System.out.println("Longest repeating substring: "+str.substring(endIndex-maxLen,endIndex)); |
| 20 | } |
| 21 | } |
Program Output
Eduinq Longest Repeating Substring Longest repeating substring: ana
Explanation
The DP table compares the string against itself at two different, non-overlapping positions (j always ahead of i), building up matching run lengths, and tracking the maximum to extract the longest repeating substring.