CheckIO The Longest Palindromic

Write a function that finds the longest palindromic substring of a given string. Try to be as efficient as possible!
If you find more than one substring you should return the one which is closer to the beginning.
Input: A text as a string.
Output: The longest palindromic substring.
Precondition: 1 < |text| ≤ 20
The text contains only ASCII characters.

解法一:
# 判断是否回文
def isPalindrome(s, start, end):
        while start < end:
            if s[start] != s[end]:
                return False
            start += 1
            end -= 1
        return True
def longest_palindromic(s):
        max, left, right = 0, 0, 0
        for i in range(len(s)):
            j = i+1
            while j < len(s):
                if isPalindrome(s, i, j):
                    if (j-i+1) > max:
                        left, right = i, j
                        max = j - i + 1
                j += 1
        print (left, right, max)
        return s[left:right+1]
循环穷举,范围从小到大。
解法二:
# 0:9 0:8 1:9 ....
def longest_palindromic(text):
    s = len(text)
    for size in range(s)[::-1]:
        for index in range(s - size):
            word = text[index:index + size + 1]
            if word == word[::-1]:
                return word
同样穷举,范围从大到小。
解法三:
from itertools import combinations as C
def longest_palindromic(text):
    subs = (text[start: end] for start, end in C(range(len(text) + 1), 2))
    print(list(C(range(len(text) + 1), 2)))
    return max((s for s in subs if s == s[::-1]), key=len)
其中的subs = (text[start: end] for start, end in C(range(len(text) + 1), 2))语句,直接
穷举出text字符串所有的子串,此方法很python。

   
   

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值