-1

In leetcode I tried to solve the "Longest Palindromic Substring" task. Here is the code:

public String longestPalindrome(String s) {
    String str = "";

    for(int i = 0; i < s.length(); i++)
    {
        for(int j = 1 + i; j < s.length() + 1; j++)
        {
            String sub = s.substring(i, j);
            if(isPalindrome(sub) && sub.length() > str.length())
            {
                str = s.substring(i, j);
            }
        }
    }
    return str;
}

public static boolean isPalindrome(String s)
{
    if(s.length() < 2)
        return true;
    else
        for(int i = 0; i < s.length() / 2; i++)
        {
            if(!(s.charAt(i) == s.charAt(s.length() - 1 - i)))
                return false;                   
        }
    return true;            
}

It works when I run it in Eclipse, but when I want to submit the solution to leetcode, it shows me an error:

Submission Result: Time Limit Exceeded
Last executed input:
"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee...

Can you tell me, what's my problem?

Michael
  • 41,989
  • 11
  • 82
  • 128

2 Answers2

0

your code is taking too much time for leetcode

for(int j = 1 + i; j < s.length() + 1; j++){
        String sub = s.substring(i, j);
        if(isPalindrome(sub) && sub.length() > str.length()){
            str = s.substring(i, j);
        }
}

in this loop you call 2 times s.substring(i, j); you can start by calling it 1 time

for(int j = 1 + i; j < s.length() + 1; j++){
        String sub = s.substring(i, j);
        if(isPalindrome(sub) && sub.length() > str.length()){
            str = sub;
        }
}

then you can search on internet :

https://www.geeksforgeeks.org/longest-palindrome-substring-set-1/

you have 2 methods brute force and optimize

Alays
  • 112
  • 2
  • 19
0

You're answer is taking an insane amount of time to run. Instead of the brute force approach try to optimize it. This is a better solution if you've trouble dealing with the dynamic approach:

class Solution {
public String longestPalindrome(String s) {
    if(s == null || s.length() < 1)
        return "";
    int start = 0;
    int end = 0;
    for(int i=0; i<s.length(); i++)
    {
        int l1 = fromMiddle(s,i,i);
        int l2 = fromMiddle(s,i,i+1);
        int l = Math.max(l1,l2);
        if(l > end - start)
        {
            start = i - ((l-1)/2);
            end = i + (l/2);
        }
    }
    return s.substring(start, end+1);
}
public int fromMiddle(String s, int left, int right)
{
    if(s == null || left > right)
        return 0;
    while(left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right))
    {
        left--;
        right++;
    }
    return right-left-1;
}
}
knk
  • 37
  • 3