简体   繁体   中英

Longest Palindromic Substring clarification

Approach #3 (Dynamic Programming) [Accepted]

To improve over the brute force solution, we first observe how we can avoid unnecessary re-computation while validating palindromes. Consider the case ''ababa''. If we already knew that ''bab'' is a palindrome, it is obvious that ''ababa'' must be a palindrome since the two left and right end letters are the same.

This yields a straight forward DP solution, which we first initialize the one and two letters palindromes, and work our way up finding all three letters palindromes, and so on...

Complexity Analysis

Time complexity : O(n^2) This gives us a runtime complexity of O(n^2).

Space complexity : O(n^2). It uses O(n^2)space to store the table.

I read the above solution to this problem online, and have some questions about it (if this isn't the correct forum to post on please let me know). This is my understanding of how to do this problem: save all the one-char palindromes. Then for each of these, if the char to the left equals the char to the right, keep it. If that condition isn't met, cease dealing with this substring. Continue this until end is reached.

Is this correct? If so, how does this translate to O(N^2) algorithm? Is it because, in the worst case scenario, we have to run through the string N times to increment each potential palindrome by one char? This part isn't intuitive to me.

Your interpretation is correct.
In the worst case we need to check all substrings with increasing length. We first check all substrings of length 1, then all substrings of length 3 and so on. In addition we also need to keep palindromes of the kind "abba" into account, thus we also need to check all candidates with even length. So in the worst case, we need to validate every possible substring of a given input-string.

Total number of substrings of a given string of length n is n(n + 1)/2

n * (n + 1) / 2 = n ^ 2 / 2 + n / 2 = O(n ^ 2)

Doing a single validation-step for a palindrome can be done in O(1) , thus the total runtime is O(n ^ 2) .

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