Reputation: 69
I am stuck on why my solution only works for some strings. For example, "sdfbananabasdf" would return "bananab", but "dtattarrattatddetartrateedre" would run in an infinite loop. Thank you in advance!
public String longestPalindrome(String s) {
if(isPalindrome(s)) {
return s;
}
String divisionOne = longestPalindrome(s.substring(0,s.length()-1));
String divisionTwo = longestPalindrome(s.substring(1,s.length()));
return (divisionOne.length() >= divisionTwo.length()) ? divisionOne : divisionTwo;
}
private boolean isPalindrome(String s) {
if(s.length() == 1) {
return true;
}
int count = s.length() / 2;
if(s.length() % 2 == 1) {
count++;
}
for(int i = 0; i < count; i++) {
if(s.charAt(i) != s.charAt(s.length() - 1 - i)) {
return false;
}
}
return true;
}
Upvotes: 0
Views: 773
Reputation: 11284
Basically, the time complexity of your algo is O(2^n)
Let say f(n)
is the function to calculate the palindrome for string with length n
, in the worst case, we can see that
f(n) = 2*f(n - 1)
f(n - 1) = 2*f(n - 2)
...
f(1) = 1
-> f(n)
time complexity is O(2^n)
So, for long string, your program will take long time to run. Like in the example, a string with 29 character will require O(2^29) or O(5*10^8) operations.
Note: Actually, each operation requires two additional substring
and a isPalindrome
operations, which will make the time complexity is O(n*2^n), not just O(2^n)
How to reduce the time complexity? Dynamic programming should be the answer
Upvotes: 3