美文网首页LeetCode
记一次=引起的血案

记一次=引起的血案

作者: cptn3m0 | 来源:发表于2019-03-15 13:16 被阅读0次

    如果从时间上看, 是用了两个小时的时间在这个问题上面.

    那么最后是什么原因呢

    有错误的python代码

    class Solution(object):
        def longestPalindrome(self, s):
            """
            :type s: str
            :rtype: str
            """
            n = len(s)
            if n==0:
              return s
            elif n ==1:
              return s
            
            dp = [[False]*n for _ in range(n)]
            
            # 表示未知解答
            max_idx = -1
            max_len = -1
            
            for i in range(n):
              dp[i][i] = True
              max_idx = i
              max_len = 1
            
            for i in range(1,n):
              if (s[i] == s[i-1]):
                dp[i-1][i] == True
                max_idx = i-1
                max_len = 2
            
    
            for strlen in range(3,n+1):
              # 注意下标
              for i in range(0,n-strlen+1):
                j = i+strlen-1
                
                if s[i] == s[j] and dp[i+1][j-1] == True:
                  dp[i][j] = True
                  if(strlen>max_len):
                    max_idx = i
                    max_len =strlen
            
            return s[max_idx:max_idx+max_len]
    
    

    正确的python代码

    class Solution(object):
        def longestPalindrome(self, s):
            """
            :type s: str
            :rtype: str
            """
            n = len(s)
            if n==0:
              return s
            elif n ==1:
              return s
            
            dp = [[False]*n for _ in range(n)]
            
            # 表示未知解答
            max_idx = -1
            max_len = -1
            
            for i in range(n):
              dp[i][i] = True
              max_idx = i
              max_len = 1
            
            for i in range(1,n):
              if (s[i] == s[i-1]):
                dp[i-1][i] == True
                max_idx = i-1
                max_len = 2
            
    
            for strlen in range(3,n+1):
              # 注意下标
              for i in range(0,n-strlen+1):
                j = i+strlen-1
                
                if s[i] == s[j] and dp[i+1][j-1] == True:
                  dp[i][j] = True
                  if(strlen>max_len):
                    max_idx = i
                    max_len =strlen
            
            return s[max_idx:max_idx+max_len]
    
    image.png

    相关文章

      网友评论

        本文标题:记一次=引起的血案

        本文链接:https://www.haomeiwen.com/subject/sgulmqtx.html