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();
        }
    };
  • 相关阅读:
    “是懒人造就了方法”——读后感
    多态性动手动脑
    数组问题随笔
    String java问题随笔
    java问题总结
    java问题随笔
    java一些问题的解答
    利用参数的值得返回来求和
    是懒人造就了方法——读后感
    大道至简读后感——JAVA伪代码
  • 原文地址:https://www.cnblogs.com/wxquare/p/6171465.html
Copyright © 2011-2022 走看看