Day46|leetcode 139. Word splitting

leetcode 139. Word splitting

Topic Link: 139. Word Splitting - LeetCode

Video Link: Dynamic Programming Complete Backpack, How to Fill Your Backpack? | LeetCode: 139. Word splitting_哔哩哔哩_bilibili

topic overview

Given a string  s and a list of strings  wordDict as dictionaries. Please judge whether you can use the words that appear in the dictionary to splice it out  s .

Note: It is not required to use all the words in the dictionary, and the words in the dictionary can be used repeatedly.

Example 1:

输入: s = "leetcode", wordDict = ["leet", "code"]
output: true
Explanation: Returns true because "leetcode" can be concatenated from "leet" and "code".

Example 2:

   输入: s = "applepenapple", wordDict = ["apple", "pen"]

   output: true

   Explanation: Returns true because "applepenapple" can be split into "apple pen apple".

   Note that you can reuse words in the dictionary.

Example 3:

    输入: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]

    output: false

train of thought

In this question, strings can be regarded as backpacks, and words can be regarded as items. The words here can be reused, which means that this is a complete backpack, and it is still a five-part dynamic rule:

1. Determine the meaning of the dp array:

dp[i] : If the string length is i, dp[i] is true, indicating that it can be split into one or more words that appear in the dictionary.

2. Determine the recursive formula:

Recursion formula: if([j, i] the substring of this interval appears in the dictionary && dp[j] is true) then dp[i] = true.

3. Array initialization:

dp[0]=true, the rest are initialized to false.

4. Determine the traversal order:

This question is asking for the number of permutations, first traversing the backpack and then traversing the items.

Why is it a permutation number, for example: s="mom", wordDict="m","o". Number m as 1 and o as 2, then mom is composed of numbers 1, 2, 1, and 112 Neither 211 nor 211, pay attention to the order, so it is the number of permutations.

5. Print the array:

139. Word Splitting

 

Code

class Solution {
public:
    bool wordBreak(string s, vector<string>& wordDict) {
        unordered_set<string> wordSet(wordDict.begin(), wordDict.end());
        vector<bool> dp(s.size() + 1, false);
        dp[0] = true;
        for (int i = 1; i <= s.size(); i++) {   // 遍历背包
            for (int j = 0; j < i; j++) {       // 遍历物品
                string word = s.substr(j, i - j); //substr(起始位置,截取的个数)
                if (wordSet.find(word) != wordSet.end() && dp[j]) {
                    dp[i] = true;
                }
            }
        }
        return dp[s.size()];
    }
};

 

Guess you like

Origin blog.csdn.net/m0_74583479/article/details/132508601