zoukankan      html  css  js  c++  java
  • longest palindromic substring

    problem description:

      given a string s, you shou find the longest palindromic substring in there

    for example:
    input :"ssaass"

    ouput:"ssaass"

    one solution: times o(n^2):

      

    class Solution(object):
        def longestPalindrome(self, s):
            """
            :type s: str
            :rtype: str
            """
            length = len(s)
            i = length
            if length == 0:
                return
            while i >1:
                j = 0
                while j <= (length - i):
                    s1 = s[j:j+i]
                    s2 = s1[::-1]
                    if s1 == s2:
                        return s1
                    j += 1
                i -= 1
            return s[0]
                        

    but in the leedcode online judge, it take a long time to exceed, so it is not good enough.Then i write anothe code according to someone write in the discussion.It's main thought is that 

    the same words(the one word also can be explainede as the same words) should be included in the center of the substring, then you can expand this substring.There should be three point. Defining i in order to limit the position of the center, it's length is form 0 to len-1.Defining j, k in order to record the bounds of the palindromic substring.Maybe i don't explain it well, so there is my code.It is written by python.

    class Solution(object):
        def longestPalindrome(self, s):
            """
            :type s: str
            :rtype: str
            """
            length = len(s)
            i = 0
            minstart = 0
            maxlen = 1
            if length <= 1:
                return s[0]
            while i< length:
                while (length - i)<maxlen/2:
                    return s[minstart:minstart+maxlen]
                j = i
                k = i
                while k<(length -1) and s[k]==s[k+1]:
                    k += 1
                i = k+1
                while k<(length -1) and j and s[j-1]==s[k+1]:
                    j -= 1
                    k += 1
                if (k - j +1)>maxlen:
                    minstart = j
                    maxlen = k-j+1
            return s[minstart:minstart+maxlen]

      

  • 相关阅读:
    golang以服务方式运行
    nginx重写规则配置
    PHP的 parse_ini_file 解析配置文件
    在Yii2中集成Markdown编辑器
    理解 is_callable
    Composer安装yii2-imagine 压缩,剪切,旋转,水印
    Yii2 基于header 实现接口版本控制
    (1) laravel php artisan list make
    php 阿里云国内短信实例
    php 云片国外短信实例
  • 原文地址:https://www.cnblogs.com/whatyouknow123/p/6677615.html
Copyright © 2011-2022 走看看