Leetcode 5. Longest Palindromic Substring

3 solutions-Dynamic Programming & Expand Around Center &

Solution 1 Dynamic Programming
The process of compute dp[i][j] is showed as following:

  1. 00
  2. 00 01
    11
  3. 00 01 02
    11 12
    22
  4. 00 01 02 03
    11 12 13
    22 23
    33
class Solution {
public String longestPalindrome(String s) {
        if(s==null){
            return "";
        }
        int l=s.length(); int max=0; String res="";
        boolean [][] dp =new boolean[l][l];
        for(int j=0;j<l;j++){
            for(int i=0;i<=j;i++){
                dp[i][j]=s.charAt(i)==s.charAt(j) && (j-i<=2||dp[i+1][j-1]);
                if(dp[i][j]){
                    if(j-i+1>max){
                        max=j-i+1;
                        res=s.substring(i, j + 1);
                    }
                }
            }
        }
        return res;
    }
}

Complexity Analysis

Time complexity : O(n2).
Space complexity : O(n2).

Solution 2 Expand Around Center
In fact, we could solve it in O(n2) time using only constant space.
We observe that a palindrome mirrors around its center. Therefore, a palindrome can be expanded from its center, and there are only 2n−1 such centers.

You might be asking why there are 2n-1 but not n centers? The reason is the center of a palindrome can be in between two letters. Such palindromes have even number of letters (such as “abba”) and its center are between the two 'b’s.

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 = expandAroundCenter(s, i, i);
        int len2 = expandAroundCenter(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 expandAroundCenter(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;
}

Complexity Analysis

Time complexity : O(n2).
Space complexity : O(1).

Solution 3 Manacher’s Algorithm

https://articles.leetcode.com/longest-palindromic-substring-part-ii/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值