leetcode -- 139. Word Break

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/word-break
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

 

思路:

1、dp[i]表示前i个字符能否拆分成wordDict里面的单词

2、运用unordered_set进行子串的查找;dp[i]为true的条件是,前j个必须也可以拆分,而且在wordDict里面可以找到拆分的单词

class Solution {
public:
    bool wordBreak(string s, vector& wordDict) {
        vector dp(s.length()+1, false);
        dp[0] = true;
        unordered_set m(wordDict.begin(), wordDict.end());
        for(int i = 1; i <= s.length(); i++){
            for(int j = 0; j < i; j++){
                if(dp[j] && m.find(s.substr(j,i-j)) != m.end()){
                    dp[i] = true;
                    break;
                }
            }
        }
        return dp[s.size()];
    }
};

 

你可能感兴趣的:(反复看,leetCode,动态规划)