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

139.单词拆分

class Solution {
public:
    bool wordBreak(string s, vector& wordDict) {
        vector dp(s.size() + 1, false);
        dp[0] = true;
        for (int i = 1; i <= s.size(); i++) {
            for (int j = 0; j < wordDict.size(); j++) {
                if (i < wordDict[j].size()) continue;
                dp[i] = dp[i - wordDict[j].size()] && (wordDict[j].compare(s.substr(i - wordDict[j].size(), wordDict[j].size())) == 0);
                if (dp[i] == true) break;//搜到了就break,避免被覆盖
            }
        }
        return dp[s.size()];
    }
};

你可能感兴趣的:(代码随想录算法训练营,c++,算法,数据结构,leetcode)