简体   繁体   中英

Finding the longest palindrome in a string using recursion

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;
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM