【问题标题】:How to turn the duplicate part in my code to a checking function?如何将我的代码中的重复部分转换为检查功能?
【发布时间】:2019-08-29 20:57:52
【问题描述】:

我为 leetcode "5. Longest Palindromic Substring" 提出了一个解决方案,其中包含部分重复代码。解决重复代码的好方法之一是创建一个函数。如何在此处将支票写入函数?我很困惑我应该返回什么来使两个变量 - 最长和 ans - 被更新。谢谢!

重复代码部分:

if len(s[l:r+1]) > longest:
    longest = len(s[l:r+1])
    ans = s[l:r+1] 

完整代码:

class Solution:
    def longestPalindrome(self, s: str) -> str:
        if len(s) == 0:
            return ''
        if len(s) == 1:
            return s

        longest = 0
        ans = ''

        for pos in range(len(s)-1):
            l, r = pos, pos
            if pos > 0 and pos < len(s) - 1 and s[pos-1] == s[pos+1]:
                l, r = pos-1, pos+1
                while l > 0 and r < len(s) - 1 and s[l-1] == s[r+1]:
                    l -= 1
                    r += 1

                # duplicate code 1
                if len(s[l:r+1]) > longest:
                    longest = len(s[l:r+1])
                    ans = s[l:r+1] 


            if s[pos] == s[pos+1]:
                l, r = pos, pos+1
                while l > 0 and r < len(s) - 1 and s[l-1] == s[r+1]:
                    l -= 1
                    r += 1

                # duplicate code 2
                if len(s[l:r+1]) > longest:
                    longest = len(s[l:r+1])
                    ans = s[l:r+1] 


        if ans == '' and len(s) > 0:
            return s[0]

        return ans

【问题讨论】:

    标签: python-3.x function


    【解决方案1】:

    重复代码块之前的 if 语句和 while 循环也大多重复,当您已经有 ans 时使用 longest 变量来跟踪 ans 的长度 - 这是一种方法你可以通过另一个函数来简化事情:

    class Solution:
        def find_longest(self, s, left, right):
            if s[left] == s[right]:
                if right - left + 1 > len(self.ans):
                    self.ans = s[left:right + 1]
                if left > 0 and right < len(s) - 1:
                    self.find_longest(s, left - 1, right + 1)
    
        def longestPalindrome(self, s: str) -> str:
            if len(s) == 1:
                return s
    
            self.ans = ''
    
            for pos in range(len(s) - 1):
                self.find_longest(s, pos, pos)
                self.find_longest(s, pos, pos + 1)
    
            return self.ans
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-02
      • 1970-01-01
      • 1970-01-01
      • 2012-12-24
      • 2023-03-23
      • 2017-03-30
      • 2022-01-24
      • 2012-05-20
      相关资源
      最近更新 更多