[LeetCode]005. Longest Palindromic Substring

本文介绍如何通过动态规划算法找到给定字符串中的最长回文子串。详细解释了动态规划的适用条件,包括子问题的重用和最优子结构,并提供了Java和Python两种语言的实现代码。讨论了算法的时间复杂度和空间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.


Solutions: use DP, find the base cases: "a", "bb", and then create the common method.

(Reference:http://leetcode.com/2011/11/longest-palindromic-substring-part-i.html)

Running time: O(n*n). (while the brute force method can cause O(n*n*n)) running time.

Space: O(n*n).


这个是LeetCode里碰到的第一道DP的题目,对于何时使用DP我的理解还很浅:

1. 子问题可被重复调用。

2. 存在最优子问题。

在接下来的做题过程中需要深入理解DP。


public class Solution {
    public String longestPalindrome(String s) {
        // Start typing your Java solution below
        // DO NOT write main() function
        int n = s.length();
        boolean[][] table = new boolean[1000][1000];
        int s_start = 0;
        int maxLength = 1;
        //use a char[] for convenience, can also use s.charAt(i) for saving space.
        char[] s1 = s.toCharArray();
        //base case1: a is a palindrome;
        for(int i=0; i<n; i++){
            table[i][i] = true;
        }
        //base case2: aa is also a palindrome;
        for(int i=0; i<n-1; i++){
            if(s1[i] == s1[i+1]){
                table[i][i+1] = true;
                maxLength = 2;
                s_start = i;
            }
        }
        //other cases: maxLength from 3 to n;
        for(int len=3; len<=n; len++){
            for(int i=0; i<n-len+1; i++){
                int j = i+len-1;
                if(s1[i]==s1[j] && table[i+1][j-1]){
                    table[i][j] = true;
                    maxLength = len;
                    s_start = i;
                }
            }
        }
        return s.substring(s_start, s_start+maxLength);
        //substring method: begin index---inclusive; end index---exclusive;
    }
}

3/24/2015 Updated

Python Solution: divide palindrome into two types: original from "a" or "aa".

Running Time: O(n*n)

class Solution:
    # add a helper function to get the longest Palindrome in a specific position. |left right|
    def getLongestPalindrome(self, s, left, right):
        while left >= 0 and right < len(s) and s[left] == s[right]:
            left -= 1
            right += 1
        return s[left+1:right]
    
    
    # @return a string
    def longestPalindrome(self, s):
        palindrome = ""
        for i in range(len(s)):
            singlePalindrome = self.getLongestPalindrome(s, i, i)#from the type "a"
            if len(singlePalindrome) > len(palindrome):
                palindrome = singlePalindrome
            doublePalindrome = self.getLongestPalindrome(s, i, i+1)#from the type "aa"
            if len(doublePalindrome) > len(palindrome):
                palindrome = doublePalindrome
        return palindrome


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值