Skip to content

refactor: LongestPalindromicSubstring #5420

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Aug 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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()];
Expand Down
Original file line number Diff line number Diff line change
@@ -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));
}
}