refactor: LongestPalindromicSubstring (#5420)

* refactor: LongestPalindromicSubstring

* checkstyle: fix formatting

---------

Co-authored-by: alxkm <alx@alx.com>
This commit is contained in:
Alex Klymenko 2024-08-28 18:35:21 +02:00 committed by GitHub
parent 45563ccbde
commit c413f3c6b2
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 30 additions and 15 deletions

View File

@ -1,25 +1,18 @@
package com.thealgorithms.dynamicprogramming;
/*
* Algorithm explanation https://leetcode.com/problems/longest-palindromic-substring/
/**
* Class for finding the longest palindromic substring within a given string.
* <p>
* A palindromic substring is a sequence of characters that reads the same backward as forward.
* This class uses a dynamic programming approach to efficiently find the longest palindromic substring.
*
*/
public final class LongestPalindromicSubstring {
private LongestPalindromicSubstring() {
}
public static void main(String[] args) {
String a = "babad";
String b = "cbbd";
String aLPS = lps(a);
String bLPS = lps(b);
System.out.println(a + " => " + aLPS);
System.out.println(b + " => " + bLPS);
}
private static String lps(String input) {
if (input == null || input.length() == 0) {
public static String lps(String input) {
if (input == null || input.isEmpty()) {
return input;
}
boolean[][] arr = new boolean[input.length()][input.length()];

View File

@ -0,0 +1,22 @@
package com.thealgorithms.dynamicprogramming;
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;
public class LongestPalindromicSubstringTest {
private static Stream<Arguments> provideTestCases() {
return Stream.of(
Arguments.of("babad", "aba"), Arguments.of("cbbd", "bb"), Arguments.of("a", "a"), Arguments.of("x", "x"), Arguments.of("", ""), Arguments.of("aaaa", "aaaa"), Arguments.of("mm", "mm"), Arguments.of("level", "level"), Arguments.of("bananas", "anana"), Arguments.of("abacabad", "abacaba"));
}
@ParameterizedTest
@MethodSource("provideTestCases")
public void testLps(String input, String expected) {
assertEquals(expected, LongestPalindromicSubstring.lps(input));
}
}