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]

      

  • 相关阅读:
    MySQL如何把varchar类型字段转换成int类型进行倒叙排序
    MySQL如何使用WITH ROLLUP函数
    MySQL数据库行转列
    SQLserver数据库如何使用SQL语句查看数据库版本
    MySQL数据库如何使用SQL语句查看数据库版本
    js刷新页面
    asp.net core控制器方法返回输出
    asp.net mvc在页面显示HTML字符串
    Convert.ToString()
    三种通信方式 转载
  • 原文地址:https://www.cnblogs.com/whatyouknow123/p/6677615.html
Copyright © 2011-2022 走看看