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

leetcode 140 Word Break II

时间:2020-05-05 11:04:03      阅读:59      评论:0      收藏:0      [点我收藏+]

标签:mem   turn   rand   ret   return   div   数组   and   ack   

leetcode 139 word break

class Solution {
public:
    bool wordBreak(string s, vector<string>& wordDict) {
        unordered_set<string> wordset(wordDict.begin(),wordDict.end());
        vector<int> memo(s.size(),-1);
        return check(s,wordset,0,memo);
    }
    
    bool check(const string &s,unordered_set<string> &wordset,int start,vector<int> &memo)
    {
        if(start>=s.size()) return true;
        if(memo[start]!=-1) return memo[start];
        for(int i=start+1;i<=s.size();++i)
        {
            if(wordset.count(s.substr(start,i-start))&&check(s,wordset,i,memo))
            {
                return memo[start]=1;
            }
        }
        return memo[start]=0;
    }
};

leetcode 140

1. 用hashset存储wordDict,查找效率高;unordered_map<int,vector<string>>记忆数组,存储从位置i开始,所有可能的情况。

class Solution {
public:
    vector<string> wordBreak(string s, vector<string>& wordDict) {
        unordered_set<string> words(wordDict.begin(),wordDict.end());
        unordered_map<int,vector<string>> memo;
        helper(s,0,words,memo);
        return memo[0];
    }
   vector<string> helper(string& s,int start,unordered_set<string>& words,unordered_map<int,vector<string>> &memo) {
        if(start>=s.size()) return {""};
        if(memo.find(start)!=memo.end()) return memo[start];
        for(int i=start+1;i<=s.size();++i) {
            string tmp=s.substr(start,i-start);
            if(words.find(tmp)!=words.end()) {
                auto vals=helper(s,i,words,memo);
                for(auto& val:vals) memo[start].push_back(tmp+(val.empty()?"":" ")+val);
            }
        }
        return memo[start];
    }
};

2. https://www.cnblogs.com/grandyang/p/4576240.html

leetcode 140 Word Break II

标签:mem   turn   rand   ret   return   div   数组   and   ack   

原文地址:https://www.cnblogs.com/LiuQiujie/p/12829611.html

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