c++ dp solution


  • 0
    H
    class Solution {
    public:
        bool wordBreak(string s, unordered_set<string>& wordDict) {
            if(wordDict.size() == 0) return false;
            int n = s.size(), maxlen = 0;
            for(string str : wordDict) maxlen = max(maxlen, int(str.size()));
            vector<bool> dp(n + 1, false);
            dp[0] = true;
            for(int j = 1; j <= n; j ++) {
                for(int i = j - 1; i >= max(j - maxlen, 0); i --) {
                    if(dp[i] && wordDict.find(s.substr(i, j-i)) != wordDict.end()) {
                        dp[j] = true;
                        break;
                    }
                }
            }
            return dp[n];
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.