Java Program to find the longest repeating sequence in a string

In this program, we need to find the substring which has been repeated in the original string more than once.

AbDFAAbdfh

In the above string, the substring bdf is the longest sequence which has been repeated twice.

The algorithm of the program is given below.

Algorithm

main()

  • STEP 1: START
  • STEP 2: DEFINE string str = “acbdfghybdf”
  • STEP 3: SET String lrs = ” “
  • STEP 4: CALCULATE length.
  • STEP 5: SET i =0. REPEAT STEP 6 to STEP 10 UNTIL i<n.
  • STEP 6: SET j =i+1. REPEAT STEP 7 to STEP 9 UNTIL j<n.
  • STEP 7: CALL lcp() in String x.
  • STEP 8: if(x.length()>lrs.length()) then lrs =x
  • STEP 9: j =j + 1
  • STEP 10: i =i +1
  • STEP 11: PRINT lrs.
  • STEP 12: END

lcp(String s, String t)

  • STEP 1: START
  • STEP 2: SET n = Math.min(s.length(), t.length())
  • STEP 3: SET i =0. REPEAT STEP 4 to STEP 5 UNTIL i<n
  • STEP 4: if(s.charAt(i) != t.charAt(i)) then RETURN s.substring(0, i)
  • STEP 5: i= i+1
  • STEP 6: RETURN s.substring(0,n)
  • STEP 7: END

Program:

  1. public class LongestRepeatingSequence {  
  2.     //Checks for the largest common prefix  
  3.     public static String lcp(String s, String t){  
  4.         int n = Math.min(s.length(),t.length());  
  5.         for(int i = 0; i < n; i++){  
  6.             if(s.charAt(i) != t.charAt(i)){  
  7.                 return s.substring(0,i);  
  8.             }  
  9.         }  
  10.         return s.substring(0,n);  
  11.     }  
  12.   
  13.     public static void main(String[] args) {  
  14.         String str = “acbdfghybdf”;  
  15.         String lrs=””;  
  16.         int n = str.length();  
  17.         for(int i = 0; i < n; i++){  
  18.             for(int j = i+1; j < n; j++){  
  19.                 //Checks for the largest common factors in every substring  
  20.                 String x = lcp(str.substring(i,n),str.substring(j,n));  
  21.                 //If the current prefix is greater than previous one  
  22.                 //then it takes the current one as longest repeating sequence  
  23.                 if(x.length() > lrs.length()) lrs=x;  
  24.             }  
  25.         }  
  26.         System.out.println(“Longest repeating sequence: “+lrs);  
  27.     }  
  28. }  

Output:

Longest repeating sequence: bdf

Leave a Comment