zoukankan      html  css  js  c++  java
  • Word Break

    Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.

    For example, given
    s = "leetcode",
    dict = ["leet", "code"].

    Return true because "leetcode" can be segmented as "leet code"

    给一个字符串s和一个字典dict,编程实现s能否由dict中组合而成。

    方案一的DFS提交TLE,方案二使用动态规划

    class Solution{
    private:
        void helper(string s,unordered_set<string>& wordDict,int start,bool& res){
            if(start == int(s.length())){
                res = true;
                return;
            }
            for(int i = start;i<int(s.size());i++){
                string word = s.substr(start,i - start + 1);
                if(wordDict.find(word) != wordDict.end() && !res){
    
                    helper(s,wordDict,i+1,res);
                }
            }
        }
    
    public:
        bool wordBreak(string s,unordered_set<string>& wordDict){
            bool res = false;
            helper(s,wordDict,0,res);
            return res;
        }
    };
    
    class Solution2{
    public:
        bool wordBreak(string s,unordered_set<string>& wordDict){
            vector<bool> res(s.size()+1,false);
            res[0] = true;
    
            for(int i=0;i<int(s.size())+1;i++){
                for(int j=0;j<i;j++){
                    if(res[j] && wordDict.find(s.substr(j,i-j)) != wordDict.end()){
                        res[i] = true;
                        break;
                    }
                }
            }
            return res.back();
        }
    };
  • 相关阅读:
    工具-pycharm-Git管理代码到GitHub
    工具-jenkins配置项目
    工具-jenkins重启服务
    工具-jenkins安装
    pycharm-管理GitHub
    博客园样式DIY
    接口测试-获取邮件授权码口令
    iOS 反射 学习 和 运用
    iOS 优化界面流畅度的探讨
    iOS 事件响应者链的学习(也有叫 UI连锁链)
  • 原文地址:https://www.cnblogs.com/wxquare/p/6171465.html
Copyright © 2011-2022 走看看