Find Repeating Pattern In String Java

Find Repeating Pattern In String Java | In the below program, we have found the repeating pattern with maximum length. In the given string there could be multiple repeating patterns, and the below program finds the repeating pattern with max length.

To solve the problem we have used Java string length(), charAt() method, substring() method, and Math class max() methods. The max() method of the Java Math class returns the maximum value among the given input values.

The length() method returns the length of the given string. The charAt() method returns the character at the given index from the given string. Similarly, the Java string substring() method returns the substring based on the given inputs.

Program to Find Repeating Pattern In String Java

public class Main {

   public static String maxRepeat(String string) {
      String string1 = "";
      int n = string.length();
      for (int i = 0; i < n; i++) {
         for (int j = i + 1; j < n; j++) {
            String x = 
               repeating(string.substring(i, n), string.substring(j, n));
            if (x.length() > string1.length()) {
               string1 = x;
            }
         }
      }
      return string1;
   }

   private static String repeating(String str, String str1) {
      int n = Math.min(str.length(), str1.length());
      for (int i = 0; i < n; i++) {
         if (str.charAt(i) != str1.charAt(i)) {
            return str.substring(0, i);
         }
      }
      return str.substring(0, n);
   }

   public static void main(String[] args) {
      String string1 = "acbdfghybdf";
      String string2 = "acbdfghybdfghabcd";
      System.out.println("Max length repeating pattern in string1: " 
             + maxRepeat(string1));
      System.out.println("Max length repeating pattern in string2: " 
             + maxRepeat(string2));
   }
}

Output:-

Max length repeating pattern in string1: bdf
Max length repeating pattern in string2: bdfgh

We have defined maxRepeat() and repeating() methods to find the repeating patterns in string Java. We have taken “acbdfghybdf” and “acbdfghybdfghabcd” as the input strings. In the string “acbdfghybdf” substring “bdf” is repeated 2 times and it is the only substring that is repeated.

In the string “acbdfghybdfghabcd”, the following sub-strings are repeated:- “bdfgh”, and “abcd”. Among these substrings “bdfgh” has max length, therefore, the maxRepeat() method returns the “bdfgh” substring. You can also try with different inputs.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *