簡體   English   中英

這兩個python程序有什么區別?

[英]What's the difference between these two python programs?

我正在解決LeetCode上的算法問題(第5個問題,如果您想先閱讀問題https://leetcode.com/problems/longest-palindromic-substring/ )。 我寫了一個python程序:

class Solution(object):
    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: str
        """
        l = 1
        if len(s) < 2:
            return s
        result = s[0]
        for end in range(1, len(s)):
            if end - (l + 1) >= 0 and s[end - (l + 1):end + 1] == s[end - (l + 1):end + 1][::-1]:
                l += 2
                result = s[end - (l + 1):end + 1]
                continue
            elif end - l >= 0 and s[end - l:end + 1] == s[end - l:end + 1][::-1]:
                l += 1
                result = s[end-l:end+1]
        return result 

當我使用“ abba ”作為輸入對其進行測試時:它輸出“ ba ”。 然后,我在討論中找到了一個python解決方案,該程序如下所示:

class Solution:
    # @return a string
    def longestPalindrome(self, s):
        if len(s) == 0: return 0
        maxLen = 1
        start = 0
        for i in xrange(len(s)):
            if i - maxLen >= 1 and s[i - maxLen - 1:i + 1] == s[i - maxLen - 1:i + 1][::-1]:
                start = i - maxLen - 1
                maxLen += 2
                continue
            if i - maxLen >= 0 and s[i - maxLen:i + 1] == s[i - maxLen:i + 1][::-1]:
                start = i - maxLen
                maxLen += 1
        return s[start:start + maxLen]

當我使用“ abba ”作為輸入對其進行測試時,它會正確輸出“ abba ”。 我是python的新手,因此對於在python中傳遞參數的問題,我總是感到困惑。 那么,誰能告訴我為什么兩個python程序得到兩個不同的結果? 提前致謝。

您更改l ,你確定是有回文,並在您使用之間l分配給該回文result 在兩個地方。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM