码迷,mamicode.com
首页 > 其他好文 > 详细

LintCode "Word Break"

时间:2015-10-03 07:20:37      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:

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

LintCode "Word Break"

标签:

原文地址:http://www.cnblogs.com/tonix/p/4853003.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!