Find Longest Palindrome in a String

package org.wesome.dsalgo;

import java.util.Objects;

public class LongestPalindromeFinder {

    static public String intermediatePalindrome(String string, int left, int right) {
        if (left > right) {
            return null;
        }
        while (left >= 0 && right < string.length() && string.charAt(left) == string.charAt(right)) {
            left--;
            right++;
        }
        return string.substring(left + 1, right);
    }

    // O(n^2)
    public static String longestPalindromeString(String origString) {
        if (Objects.isNull(origString)) {
            return null;
        }
        String longest = origString.substring(0, 1);
        for (int i = 0; i < origString.length() - 1; i++) {
            /*  odd cases like aba  */
            String palindrome = intermediatePalindrome(origString, i, i);
            if (palindrome.length() > longest.length()) {
                longest = palindrome;
            }
            /*  even cases like abba */
            palindrome = intermediatePalindrome(origString, i, i + 1);
            if (palindrome.length() > longest.length()) {
                longest = palindrome;
            }
        }
        return longest;
    }
}
package org.wesome.dsalgo;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import static org.wesome.dsalgo.LongestPalindromeFinder.longestPalindromeString;

public class BinarySearchTreeTest {
    @Test
    void longestPalindromeStringTest1() {
        Assertions.assertEquals("wesome.emosew", longestPalindromeString("awesome.emosew"));
    }

    @Test
    void longestPalindromeStringTest2() {
        Assertions.assertEquals("ailihphilia", longestPalindromeString("abcailihphiliaxyz"));
    }

    @Test
    void longestPalindromeStringTest3() {
        Assertions.assertEquals("step on no pets", longestPalindromeString("step on no pets"));
    }

    @Test
    void longestPalindromeStringTest4() {
        Assertions.assertEquals("hi madam ih", longestPalindromeString("hi madam ih"));
    }
}
plugins {
    id 'java'
    id "io.freefair.lombok" version "6.2.0"
}

group = 'org.wesome'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = JavaVersion.VERSION_1_8

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter:5.6.2'
}

test {
    useJUnitPlatform()
}

 

follow us on