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?
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