Leetcode-139. Word Break(Medium)-python

本文详细解析了LeetCode题目Word Break(问题139)的解决方法,通过对比暴力递归和动态规划两种算法,阐述了如何判断一个字符串能否由字典中的单词组成。动态规划方案显著提高了问题的解决效率。

Leetcode-139. Word Break(Medium)-python

问题描述:

Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words.

Note:

The same word in the dictionary may be reused multiple times in the segmentation.
You may assume the dictionary does not contain duplicate words.

给一个字符串和一个由字符串中字母组成的字典数组,让我们判断这个字符串是否可以由字典中字符组成。

字典中不包含重复的字符,但是同一个字符可以使用多次来组成字符串。

Example:

Example 1:

Input: s = "leetcode", wordDict = ["leet", "code"]
Output: true
Explanation: Return true because "leetcode" can be segmented as "leet code".
Example 2:

Input: s = "applepenapple", wordDict = ["apple", "pen"]
Output: true
Explanation: Return true because "applepenapple" can be segmented as "apple pen apple".
             Note that you are allowed to reuse a dictionary word.
Example 3:

Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
Output: false

解法一(暴力递归Time Limit Exceeded):

首先想到的就是字符串中每一个长度的字符都判断一遍,这种做法最容易想到,但是时间复杂度太高了。通过不了。

class Solution:
    def wordBreak(self, s: str, wordDict: List[str]) -> bool:
        if not s:
            return True
        for i in range(len(s)):
            temp = s[:i+1]
            if temp in wordDict:
                if self.wordBreak(s[i+1:],wordDict):
                    return True
                else:
                    continue
                    
        return False

解法二(DP):

动态规划的求解。先附上两个链接。
https://www.cnblogs.com/grandyang/p/4257740.html
https://blog.youkuaiyun.com/fuxuemingzhu/article/details/79368360
https://www.youtube.com/watch?v=pYKGRZwbuzs
动态规划的解法还是不是特别清楚,dp数组中存得是每一个长度是否可以由字典组成。比如dp[i]表示从开始位置到长度为i的字串是否能由字典组成。因为表示的是长度的字符所以,我们设置dp的长度为len(s) + 1,因为还有0值也即是长度为0的子串(空子串)。最后我们返回dp[-1]的值,而状态转移方程是dp[i] = True if dp[k] and dp[k:i] in worddict。

class Solution:
    def wordBreak(self, s: str, wordDict: List[str]) -> bool:
        if not s:
            return True
        dp = [False] * (len(s) + 1)
        dp[0] = True
        for i in range(1,len(s) + 1):
            for j in range(i):
                if dp[j] and s[j:i] in wordDict:
                    dp[i] = True
        return dp.pop()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值