Thursday 2 December 2021

Program to find the longest repeating sequence in a string

Longest_repeating

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.

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

string 1

"acbdfghybdf"

Program

class Longest_repeating {

  public static String lcp(String s, String t){

   int n = Math.min(s.length(),t.length());

    for (int i = 0; i < n; i++){

    if (s.charAt(i) != t.charAt(i)){

     return s.substring(0,i);

     }

  }

   return s.substring(0,n);

 }

  public static void main(String[] args)   {

    //declare string

   String str1="acbdfghybdf";

  String lrs="";

  int n = str.length();

  for (int i = 0; i < n; i++){

   for (int j = i+1; j < n; j++){

  //Checks for the largest common factors in every substring

    String x = lcp(str.substring(i,n),str.substring(j,n));

     if (x.length() > lrs.length()) lrs=x;

   }

 }

   System.out.println( "Longest repeating sequence: " +lrs);

    }

   }

output

Longest repeating sequence: bdf

Theory

No comments:

Post a Comment

How do you select data from a table in SQL?

Create Table How do you select data a table in SQL? The SELECT statement is used to se...