原理简单但手写总是出问题的编程题

最长回文子串

def solution(s):
    maxlen = 0
    maxstr = ''
    for i in range(len(s)):
        for j in range(i+1):
            if len(s[j:i+1])<=maxlen:#优化,减少循环
                break
            if s[j:i+1]==s[j:i+1][::-1] and len(s[j:i+1])>maxlen:
                    maxlen = len(s[j:i+1])
                    maxstr = s[j:i+1]
    print(maxlen)
    print(maxstr)

python合并有序链表

class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:
    def mergeTwoLists(self, l1, l2):
        if l1 is None and l2 is None:
            return None
        new_list = ListNode(0)
        pre = new_list
        while l1 is not None and l2 is not None:
            if l1.val < l2.val:
                pre.next = l1
                l1 = l1.next
            else:
                pre.next = l2
                l2 = l2.next
            pre = pre.next
        if l1 is not None:
            pre.next = l1
        else:
            pre.next = l2
        return new_list.next
posted @ 2020-09-25 19:15  yourText  阅读(117)  评论(0编辑  收藏  举报