代码随想录训练营第四十六天|LeetCode 139单词拆分

LeetCode 139单词拆分

题目链接:139.单词拆分

class Solution {
public:
    bool wordBreak(string s, vector<string>& wordDict) {
        unordered_set<string> uset(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) {//子字符串的开始位置
            //所以截取的子字符串长度为i-j
                if (uset.find(s.substr(j, i - j)) != uset.end() && dp[j]) dp[i] = true;
            }
        }
        return dp[s.size()];
    }
};
  • 时间复杂度:O(n^3),因为substr返回子串的副本是O(n)的复杂度(这里的n是substring的长度)
  • 空间复杂度:O(n)

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