【c++】leetcode139 单词拆分

1.题目

https://leetcode.cn/problems/word-break/description/

2.解法

动态规划求解

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

注意:

string.substr(start, length);

https://blog.csdn.net/qq_28414091/article/details/126864846

猜你喜欢

转载自blog.csdn.net/qq_35975447/article/details/128839688