Add Longest Repeated Substring algorithm (#7286)

* Add Longest Repeated Substring algorithm

Implement LongestRepeatedSubstring in the strings package using the
existing SuffixArray and Kasai's algorithm for LCP array construction.
Includes parameterized unit tests covering typical and edge cases.

* style: reformat test file per clang-format and add coverage test

---------

Co-authored-by: Çağlar Eker <eker.caglar@hepsiburada.com>
This commit is contained in:
Çağlar Eker
2026-02-22 21:15:22 +03:00
committed by GitHub
parent 109df1f398
commit 12935c291d
2 changed files with 116 additions and 0 deletions

View File

@@ -0,0 +1,33 @@
package com.thealgorithms.strings;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class LongestRepeatedSubstringTest {
@ParameterizedTest(name = "\"{0}\" -> \"{1}\"")
@MethodSource("provideTestCases")
void testLongestRepeatedSubstring(String input, String expected) {
assertEquals(expected, LongestRepeatedSubstring.longestRepeatedSubstring(input));
}
private static Stream<Arguments> provideTestCases() {
return Stream.of(Arguments.of("banana", "ana"), Arguments.of("abcabc", "abc"), Arguments.of("aaaa", "aaa"), Arguments.of("abcd", ""), Arguments.of("a", ""), Arguments.of("", ""), Arguments.of(null, ""), Arguments.of("aab", "a"), Arguments.of("aa", "a"), Arguments.of("mississippi", "issi"));
}
@ParameterizedTest(name = "\"{0}\" -> LCP={1}")
@MethodSource("provideLcpTestCases")
void testBuildLcpArray(String input, int[] expectedLcp) {
int[] suffixArray = SuffixArray.buildSuffixArray(input);
assertArrayEquals(expectedLcp, LongestRepeatedSubstring.buildLcpArray(input, suffixArray));
}
private static Stream<Arguments> provideLcpTestCases() {
return Stream.of(Arguments.of("banana", new int[] {1, 3, 0, 0, 2}), Arguments.of("ab", new int[] {0}));
}
}