zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    hibernate一对多查询
    hibernate关联关系查询
    Cookie&&session
    JSP&&EL&&JSTL
    servlet下的request&&response
    servlet
    mysql命令
    html小结
    RabbitMQ初步学习和使用
    爬虫简单案例
  • 原文地址:https://www.cnblogs.com/tonix/p/4853003.html
Copyright © 2011-2022 走看看