Finding the longest repeating substring.
Here’s a Java program that finds the longest repeating substring in a given string:
import java.util.HashMap; import java.util.Map; public class LongestRepeatingSubstring { public static String findLongestRepeatingSubstring(String str) { int n = str.length(); Map<String, Integer> substrings = new HashMap<>(); // Generate all possible substrings for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { String substring = str.substring(i, j); int count = substrings.getOrDefault(substring, 0); substrings.put(substring, count + 1); } } String longestSubstring = ""; // Find the longest repeating substring for (Map.Entry<String, Integer> entry : substrings.entrySet()) { String substring = entry.getKey(); int count = entry.getValue(); if (count > 1 && substring.length() > longestSubstring.length()) { longestSubstring = substring; } } return longestSubstring; } public static void main(String[] args) { String input = "ABABABCABABABCAB"; String longestRepeatingSubstring = findLongestRepeatingSubstring(input); System.out.println("Longest repeating substring: " + longestRepeatingSubstring); } }
In this program, we use a `HashMap` to store the substrings and their counts. We iterate over the input string and generate all possible substrings, excluding the substring starting from the same index (to avoid duplicate substrings). We store each substring in the `HashMap` and increment its count if it already exists.
After that, we iterate over the substrings and find the one with a count greater than 1 (indicating it repeats) and the maximum length. The longest repeating substring is stored in the `longestSubstring` variable.
In the `main` method, we provide an example input string “ABABABCABABABCAB” and call the `findLongestRepeatingSubstring` method to get the result. Finally, we print the longest repeating substring.
Please note that this program finds the longest repeating substring in terms of characters, not necessarily consecutive. If you need to find consecutive repeating substrings, you would need to modify the program accordingly.