139. Word Break 单词拆分

题目链接
tag:

  • Medium;
  • DP;

question:
  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 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

思路:
  DP解法的两大难点,定义dp数组跟找出状态转移方程,先来看dp数组的定义,这里我们就用一个一维的dp数组,其中dp[i]表示范围[0, i)内的子串是否可以拆分,注意这里dp数组的长度比s串的长度大1,是因为我们要处理空串的情况,我们初始化dp[0]为true,然后开始遍历。注意这里我们需要两个for循环来遍历,我们必须要遍历所有的子串,我们用j把[0, i)范围内的子串分为了两部分,[0, j) 和 [j, i),其中范围 [0, j) 就是dp[j],范围 [j, i) 就是s.substr(j, i-j),其中dp[j]是之前的状态,已经算出来了,可以直接用,只需要在字典中查找s.substr(j, i-j)是否存在了,如果二者均为true,将dp[i]赋为true,并且break掉,此时就不需要再用j去分[0, i)范围了,因为[0, i)范围已经可以拆分了。最终我们返回dp数组的最后一个值,代码如下:

class Solution {
public:
    bool wordBreak(string s, vector<string>& wordDict) {
        // DP
        unordered_set<string> wordSet(wordDict.begin(), wordDict.end());
        vector<bool> dp(s.size() + 1);
        dp[0] = true;
        for (int i = 0; i < dp.size(); ++i) {
            for (int j = 0; j < i; ++j) {
                if (dp[j] && wordSet.count(s.substr(j, i - j))) {
                    dp[i] = true;
                    break;
                }
            }
        }
        return dp.back();
    }
};
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 动态规划(Dynamic Programming) 本文包括: 动态规划定义 状态转移方程 动态规划算法步骤 最长...
    廖少少阅读 3,391评论 0 18
  • 最长递增子序列 给定一个无序的整数数组,找到其中最长上升子序列的长度。示例:输入: [10,9,2,5,3,7,1...
    little田同学阅读 385评论 0 1
  • 题目: Given a non-empty string s and a dictionary wordDict ...
    BlueSkyBlue阅读 450评论 0 0
  • Given a non-empty string s and a dictionary wordDict cont...
    ShutLove阅读 855评论 0 2
  • 偶然间进了一个云配偶夸夸群,此群成立的目的就是描述各种云七彩的颜色,并给予相互鼓励,共同创建和谐美好的社会。 因为...
    谁用了我的笔名木D阅读 401评论 0 2