HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

"Longest Palindromic Substring" challenge solution is inefficient

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
solutionchallengesubstringinefficientlongestpalindromic

Problem

I am trying to solve the Longest Palindromic Substring problem on LeetCode, and I have come up with a DP solution pasted below:

public class Solution {
    String      string;
    boolean[][] visited;
    String[][]  results;

    private boolean isPalindrome(String s){
        String test = new StringBuilder(s).reverse().toString();
        if(test.equals(s)) return true; else return false;
    }

    private String maxLengthString(String... args){
        String result = new String();
        for(String arg:args){
            if(arg.length() > result.length()) result = arg;
        }
        return result;
    }

    private String findLongestPalindrome(int start,int end){
        if(start >= end) return new String();
        else if(start >= string.length() || start  string.length()) return new String();
        else{
            if(visited[start][end-1] == true) return results[start][end-1];
            String result = new String();
            if(this.isPalindrome(string.substring(start,end)))
                result = maxLengthString(string.substring(start,end),
                                        findLongestPalindrome(start+1,end),
                                        findLongestPalindrome(start,end-1));
            else result = maxLengthString(findLongestPalindrome(start+1,end),
                                          findLongestPalindrome(start,end-1));
            visited[start][end-1] = true;
            results[start][end-1] = result;
            return result;
        }
    }

    public String longestPalindrome(String s) {
        // Start typing your Java solution below
        // DO NOT write main() function

        string = s;
        visited = new boolean[s.length()][s.length()];
        results = new String[s.length()][s.length()];

        return findLongestPalindrome(0,s.length());
    }
}


The algorithm is quite straightforward, but the online judge complains about it not being efficient enough. I am just wondering if this al

Solution

Why is it slow?

The input string S can be up to 1000 characters.

Your DP solution considers all \$\mathcal{O}(|S|^2)\$ substrings of S and you're checking for each of these substrings, if it is a palindrome, in linear time in terms of the length of this substring.

Faster solutions

You can do it easily in \$\mathcal{O}(|S|^2)\$ using a polynomial hashing technique.

There are of course more sophisticated and linear solutions based on the famous Manacher algorithm.

Context

StackExchange Code Review Q#29434, answer score: 3

Revisions (0)

No revisions yet.