C/C++教程

[LeetCode] 5. Longest Palindromic Substring _Medium tag: Two pointers

本文主要是介绍[LeetCode] 5. Longest Palindromic Substring _Medium tag: Two pointers,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

Given a string s, return the longest palindromic substring in s.

 

Example 1:

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

Example 2:

Input: s = "cbbd"
Output: "bb"

Example 3:

Input: s = "a"
Output: "a"

Example 4:

Input: s = "ac"
Output: "a"

 

Constraints:

  • 1 <= s.length <= 1000
  • s consist of only digits and English letters (lower-case and/or upper-case),

Ideas:

1. 利用 来建一个palin, T: O(n * n) , S: O(n * n), 然后再用两个for loop 去看是否为palin,再更新ans及ans_length, 但是Leetcode上Time Limit Exceeded.

Code

class Solution:
    def longestPalindrome(self, s: str) -> str:
        palin = self.generatePalin(s)
        n = len(s)
        ans_length, ans = 1, s[0]
        for i in range(n):
            for j in range(i, n):
                if palin[i][j] and j - i + 1 > ans_length:
                    ans_length, ans = j - i + 1, s[i : j + 1]
        return ans
    
    
    
    def generatePalin(self, s):
        n = len(s)
        palin = [[False] * n for _ in range(n)]
        for i in range(n):
            palin[i][i] = True
            if i > 0:
                palin[i - 1][i] = s[i] == s[i - 1]
        for width in range(2, n):
            for start in range(n):
                if start + width < n and s[start] == s[start + width]:
                    palin[start][start + width] = palin[start + 1][start + width - 1]
        return palin

 

Idea 2: 用一个helper function, 每次往两边衍生, 如果当前是palin的话,然后再更新ans

Code

class Solution:
    def longestPalindrome(self, s: str) -> str:
        #palin = self.generatePalin(s)
        n = len(s)
        ans =s[0]
        for i in range(n):
            # odd case, ex: "aba"
            odd = self.helper(s, i, i)
            if len(odd) > len(ans):
                ans = odd
            
            # even case
            even = self.helper(s, i, i + 1)
            if len(even) > len(ans):
                ans = even
        return ans
    
    
    
    def helper(self, s, l, r):
        while l >=0 and r <len(s) and s[l] == s[r]:
            l-=1
            r+=1
        return s[l+1:r]

 

这篇关于[LeetCode] 5. Longest Palindromic Substring _Medium tag: Two pointers的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!