LintCode "Word Break"

LeetCode AC code failed last case with TLE. We need further pruning - we only enumerate all possible lengths of all dict words.

class Solution {
    vector<int> rec;
public:
    /**
     * @param s: A string s
     * @param dict: A dictionary of words dict
     */
    bool wordBreak(string s, unordered_set<string> &dict) {
        if (s.length() == 0) return true;
        if (dict.size() == 0) return false;
        
        unordered_set<int> lens;
        for(auto &w : dict)
            lens.insert(w.length());
        
        vector<bool> dp(s.length() + 1, false);  
        dp[0] = true;  
        for (int i = 1; i < s.length() + 1; i++) 
        {  
            for(auto l : lens)
            {
                int start = i - l;
                if(start >= 0)
                {
                    if (dp[start] && dict.find(s.substr(start, l)) != dict.end()) 
                    {  
                        dp[i] = true;  
                        break; 
                    }  
                }
            }
        }  
        return dp[s.length()];  
    }
};
View Code
原文地址:https://www.cnblogs.com/tonix/p/4853003.html