Word Break

Med Given a string s and a dictionary of words dict, determine if s can be break into a space-separated sequence of one or more dictionary words.

Thoughts

问给定的str能否由字典内元素拼凑而成。也就是找是否存在划分,action为枚举可能的划分,DP。

Code

/*
 * @lc app=leetcode id=139 lang=cpp
 *
 * [139] Word Break
 */

// @lc code=start
class Solution {
public:
    bool wordBreak(string s, vector<string>& wordDict) {
        unordered_set<string> words(wordDict.begin(), wordDict.end());
        const int N = s.size();
        int mx_len = 0;
        for (const auto w : wordDict) {
            mx_len = max((int)w.length(), mx_len);
        }
        vector<bool> dp(N + 1, false);
        dp[0] = true;
        for (int i = 1; i <= N; ++i) {
            for (int j = max(i - 1 - mx_len, 0); j < i; ++j) {
                if (dp[j] && words.count(s.substr(j, i - j))) {
                    dp[i] = true;
                    break;
                }
            }
        }
        return dp[N];
    }
};
// @lc code=end

Analysis

TC: O(n2)O(n^2)

需要作一点小优化,否则l**tcode会超时。

Last updated

Was this helpful?