代码随想录算法训练营第46天|139. 单词拆分

139. 单词拆分

class Solution {
public:
    bool wordBreak(string s, vector& wordDict) {
        auto wordDictSet = unordered_set  ();
        for (auto word: wordDict) {
            wordDictSet.insert(word);
        }

        auto dp = vector  (s.size() + 1);
        dp[0] = true;
        for (int i = 1; i <= s.size(); ++i) {
            for (int j = 0; j < i; ++j) {
                if (dp[j] && wordDictSet.find(s.substr(j, i - j)) != wordDictSet.end()) {
                    dp[i] = true;
                    break;
                }
            }
        }

        return dp[s.size()];
    }
};

你可能感兴趣的:(算法,leetcode,动态规划)