zoukankan      html  css  js  c++  java
  • 200. 最长回文子串

    200. 最长回文子串

    中文English

    给出一个字符串(假设长度最长为1000),求出它的最长回文子串,你可以假定只有一个满足条件的最长回文串。

    样例

    样例 1:

    输入:"abcdzdcab"
    输出:"cdzdc"
    

    样例 2:

    输入:"aba"
    输出:"aba"
    

    挑战

    O(n2) 时间复杂度的算法是可以接受的,如果你能用 O(n) 的算法那自然更好。

    输入测试数据 (每行一个参数)如何理解测试数据?
    时间复杂度:O(n2)  空间复杂度:常数
    class Solution:
        """
        @param s: input string
        @return: the longest palindromic substring
        """
        """
        大致思路:
        1.首先呢,给个方法,判断当前字符串是否是回文子串
        2.初始化p=0,res =None,假如当前回文子串长度大于p,则更新res
        3.外层循环s,内层依次加1循环,1,3,5,7,一直到长度为s为止,最终返回res
        """
        def longestPalindrome(self, s):
            # write your code here
            p,res = 0,None
            
            for i in range(len(s)):
                j = i + 1
                while j  <= len(s):
                    #判断是否是回文字符串,并且和p进行比较,如果小于,则更新
                    if s[i:j] == s[i:j][::-1] and  len(s[i:j]) > p:
                        p = len(s[i:j])
                        res = s[i:j]
                    j += 1
            return res

     双指针写法:

    class Solution:
        """
        @param s: input string
        @return: the longest palindromic substring
        """
        '''
        大致思路:
        1.给出一个方法,判断是否是回文子串,双指针,只要是不等,则break,否则继续判断下去.然后初始化length = 0,如果长度大于length,则更新
        '''
    
        def longestPalindrome(self, s):
            if not s or s == '':return 0
            
            #初始化
            l = 0
            res = ''
            for i in range(len(s)):
                new_res = self.isPalindrome(s,i,i) if len(self.isPalindrome(s,i,i)) > len(self.isPalindrome(s,i,i+1)) else self.isPalindrome(s,i,i + 1)
            
                if len(new_res) > l:
                    res = new_res
                    l = len(new_res)
            return res
    
        def isPalindrome(self,s,i,j):
            while i >= 0 and j <= len(s) - 1:
                if (s[i] != s[j]):
                    break
                i -= 1
                j += 1
            return s[i+1:j]
  • 相关阅读:
    005 字符串
    004 变量
    003 python中的内置函数
    002 如何在一台PC上装两个版本的python
    在github上创建新的分支(包括管理分支)
    使用git工具上传自己的程序到github上
    004 Java的一次面试题,学长列举
    为什么分布式一定要有Redis?
    027 ResourceBundle.getBundle方法
    Jenkins下载安装
  • 原文地址:https://www.cnblogs.com/yunxintryyoubest/p/12950802.html
Copyright © 2011-2022 走看看