5 Longest Palindromic Substring
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
1 | Example 1: |
Problem Analysis
Need a boolean do array to record the relationship between the left and right boundary.
dp[i][j] = i equal to the right pointer and j equal to left pointer, true means there is a palindromic string between two boundaries.
Algorithm Analysis
Given a leftLongest and rightLongest integer to track the longest length of the results.
Used a left and right pointers to loop through our string. Right pointer goes forward and left pointer follows the right pointer starting from 0.
Used a boolean variable isInnerParlidrom to check left + 1 and right - 1. (If right - left <= 2
it means the inner string always be Parlidrom)
Check the current characters pointed by these two pointers and the state of the inner word. If the current string is Palindrome, update the left and right longest records.
Time Complexity Analysis - Dynamic Programming
Time: O(n^2)
Space: O(n^2)
Code Implementation
1 | class Solution { |
Follow up - More efficient
The basic idea is to traverse all the palindromes with its pivot range from the first char of string s to the last char of string s (consider both even length and odd length situation). Use StringBuilder to minimize space complexity.
1 | public class Solution { |