每日一题--最长回文子串

普通暴力法

暴力法的原理很简单,就是挨个判断子串是否为回文子串,但直接暴力法是无法通过的,所以可以在其基础上去除掉不必要的判断,代码如下:

class Solution:
    def IsPalindrome(self, s: str):
        reverse = s[::-1]

        if s==reverse:
            return True
        else:
            return False

    def longestPalindrome(self, s: str) -> str:
        length = len(s)
        if length == 0 or length == 1:
            return s
        max_length = 1
        result = s[0]
        for i in range(length):
            for j in range(length, i, -1):
                substr = s[i:j]
                if self.IsPalindrome(substr):
                    if j - i > max_length:
                        max_length = j - i
                        result = substr
                    break
            if max_length >= length - i:
                break
        return result

动态规划

当然,这不是好的解法,进一步的,我们思考这个问题,上述判断回文字串的一个很明显的缺陷就是过多的重复判断,例如当我们知道s_{i+1,j-1}为回文子串时,那么我们只需要知道s_{i}==s_{j},我们就可以判断s_{i,j}为回文子串,基于此,我们就可以进行递归判断,使得复杂度降为O(n^2):

class Solution:
    def longestPalindrome(self, s: str) -> str:
        if not s:
            return ""
            
        n = len(s)
        is_palindrome = [[False] * n for _ in range(n)]
        
        for i in range(n):
            is_palindrome[i][i] = True
        for i in range(1, n):
            is_palindrome[i][i - 1] = True
            
        longest, start, end = 1, 0, 0
        for length in range(1, n):
            for i in range(n - length):
                j = i + length
                is_palindrome[i][j] = s[i] == s[j] and is_palindrome[i + 1][j - 1]
                if is_palindrome[i][j] and length + 1 > longest:
                    longest = length + 1
                    start, end = i, j
                    
        return s[start:end + 1]

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中求解最文子串的方法有多种,其中包括暴力求解和动态规划等。根据引用[1]和引用中的代码示例,我们可以看到两种暴力求解的方法。这些方法通过列举所有可能的子串并判断是否为文串来找到最文子串。 根据引用中的代码示例,我们可以看到一种使用动态规划的方法。这种方法通过构建一个二维数组来保存子串的文信息,并利用之前计算过的结果来计算新的结果。 根据引用中的代码示例,可以使用以下方法来求解最文子串: 1. 定义一个字符串变量`str`,用于存储最文子串。 2. 定义一个整数变量`longest`,用于存储最文子串度。 3. 使用两层循环,外层循环遍历字符串`s`的每一个字符,内层循环从外层循环的字符开始遍历到字符串`s`的最后一个字符。 4. 在内层循环中,使用`substring`方法获取当前子串。 5. 调用`isPalindromes`方法判断当前子串是否为文串,并且度大于`longest`。 6. 如果是文串且度大于`longest`,则更新`str`和`longest`的值。 7. 返`str`作为最文子串。 根据引用中的代码示例,可以使用以下方法来求解最文子串: 1. 定义一个整数变量`len`,用于存储字符串`s`的度。 2. 如果`len`小于2,直接返`s`作为最文子串。 3. 定义一个整数变量`maxLen`,用于存储最文子串度。 4. 定义一个整数变量`begin`,用于存储最文子串的起始下标。 5. 将字符串`s`转换为字符数组`chars`。 6. 使用两层循环,外层循环遍历字符串中的每一个字符,内层循环从外层循环的字符开始遍历到字符串的最后一个字符。 7. 在内层循环中,判断`chars`数组中从`i`到`j`的子串是否为文串,并且度大于`maxLen`。 8. 如果是文串且度大于`maxLen`,则更新`maxLen`和`begin`的值。 9. 返从`begin`到`begin+maxLen`的子串作为最文子串。 以上是两种求解最文子串的方法,你可以根据实际需求选择其中一种方法进行使用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值