5. Longest Palindromic Substring - Medium

Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

Example 1:

Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.

Example 2:

Input: "cbbd"
Output: "bb"
 
M1: dp
dp[i][j]表示s.substring(i, j)是否是一个palindromic string
time: O(n^2), space: O(n^2)
 
M2: expand around corner
遍历s,对每一个可能的位置都用helper function check能否expand around corner并找出expand的长度。因为center可能在字母位置也可能在两个字母中间位置,对两个位置都要expand并找出较大的。最后更新一下start, end的位置,如果len > start - end
time: O(n^2), space: O(1)
class Solution {
    public String longestPalindrome(String s) {
        if(s == null || s.length() < 1) {
            return "";
        }
        int start = 0, end = 0;
        for(int i = 0; i < s.length(); i++) {
            int len1 = helper(s, i, i);
            int len2 = helper(s, i, i + 1);
            int len = Math.max(len1, len2);
            if(len > end - start) {
                start = i - (len - 1) / 2;
                end = i + len / 2;
            }
        }
        return s.substring(start, end + 1);
    }
    
    private int helper(String s, int left, int right) {
        int l = left, r = right;
        while(l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) {
            l--;
            r++;
        }
        return r - l - 1;
    }
}
 
M3: Manacher's Algorithm
time: O(n), space: O()
 
posted @ 2019-01-25 03:00  fatttcat  阅读(106)  评论(0编辑  收藏  举报