139. Word Break

problem description

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

algorithm thought

这题可以很快相出回溯解法,匹配到一个进入下一个函数即可,但是这样会有很多重复的计算。

可以用动态规划解决,用一个数组保存结果,每一位表示0-i长度的s能匹配。遍历s,如果当前i开始的substring中,能和wordDict匹配,并且当前dp[i]=true的话,那么substirng的index的是true,最后返回数组最后一位即可

code

class Solution {
public:
    bool wordBreak(string s, vector<string>& wordDict) {
        vector<bool> res(s.size()+1,false);
        res[0]=true;
        for(int i=0;i<s.size();++i){
            for(int j=0;j<wordDict.size();++j){
                int sz=wordDict[j].size();
                int pos=i+1-sz;
                if(pos>=0&&s.substr(pos,sz)==wordDict[j]&&res[pos]){
                    res[i+1]=true;
                    break;
                }
            }
        }
        return res.back();
    }
};

algorithm analysis

设s长度为m,wordDict长度为n,每个word平均长度是k,最后时间复杂度是O(mnk)

Last updated