每日leetcode4.6(单词拆分+合并K个有序链表)-待更新

本文分享了如何使用动态规划解决LeetCode中的单词拆分问题,并提供了一种优化算法来合并K个已排序链表。通过实例展示了Python代码实现,适合前端、后端开发者进阶练习。

每日leetcode两题4.5-单词拆分

139、单词拆分

我的初步解法
from typing import List


class Solution:
    def match(self, s: str, y: str) -> bool:
        if len(s) < len(y):
            return False
        for i in range(len(y)):
            if s[i] != y[i]:
                return False
        return True

    def wordBreak(self, s: str, wordDict: List[str]) -> bool:
        l = len(s)
        dp = [[0] * (l + 1) for col in range(l + 1)]
        for i in range(l + 1):
            dp[i][i] = 1
        for j in range(1, l + 1):
            for i in range(l + 1 - j):
                for k in wordDict:
                    if dp[i][i + j] == 0 and self.match(s[i:i + j], k):
                        dp[i][i + j] = dp[i + len(k)][i + j]
        return dp[0][l] == 1


if __name__ == '__main__':
    x = Solution()
    s = 'applepenapple'
    wordDict = ["apple", "pen"]
    print(x.wordBreak(s, wordDict))
    print(x.match(s[0:8], wordDict[0]))

23、合并K个排序链表(hard)

初步解法如下,优化解法应该用优先队列,了解c++中的优先队列
from typing import List


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


class Solution:
    def mergeKLists(self, lists: List[ListNode]) -> ListNode:
        l = len(lists)
        ans = ListNode()
        temp = ans
        minI = 0
        while minI != -1:
            minL = 100000
            minI = -1
            for i in range(l):
                if lists[i] != None and lists[i].val < minL:
                    minL = lists[i].val
                    minI = i
            if minI != -1:
                temp.next = ListNode(minL)
                temp = temp.next
                lists[minI] = lists[minI].next
        return ans.next


if __name__ == '__main__':
    x = Solution()
    y = ListNode()
    y.next = ListNode(6)
    z = ListNode(3)
    z.next = ListNode(7)
    k = x.mergeKLists([y, z])
    print(k.val)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值