Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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
posted on 2015-10-03 07:02  Tonix  阅读(209)  评论(0编辑  收藏  举报