首页 > 其他 > 详细

139. Word Break

时间:2019-02-13 00:24:36      阅读:67      评论:0      收藏:0      [点我收藏+]

标签:false   word   leetcode   you   words   sed   enc   break   con   

Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words.

Note:

  • The same word in the dictionary may be reused multiple times in the segmentation.
  • You may assume the dictionary does not contain duplicate words.

Example 1:

Input: s = "leetcode", wordDict = ["leet", "code"]
Output: true
Explanation: Return true because "leetcode" can be segmented as "leet code".

Example 2:

Input: s = "applepenapple", wordDict = ["apple", "pen"]
Output: true
Explanation: Return true because "applepenapple" can be segmented as "apple pen apple".
             Note that you are allowed to reuse a dictionary word.

Example 3:

Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
Output: false

 

Approach #1: 

class Solution {
public:
    bool wordBreak(string s, vector<string>& wordDict) {
        unordered_set<string> _wordDict(wordDict.begin(), wordDict.end());
        return wordBreak(s, _wordDict);
    }
    
    bool wordBreak(const string& s, const unordered_set<string>& wordDict) {
        if (memo_.count(s)) return memo_[s];
        if (wordDict.count(s)) return memo_[s] = true;
        for (int j = 1; j < s.length(); ++j) {
            string left = s.substr(0, j);
            string right = s.substr(j);
            if (wordDict.count(right) && wordBreak(left, wordDict))
                return memo_[s] = true;
        }
        return memo_[s] = false;
    }
    
private:
    unordered_map<string, bool> memo_;
};

  

 

139. Word Break

标签:false   word   leetcode   you   words   sed   enc   break   con   

原文:https://www.cnblogs.com/ruruozhenhao/p/10367558.html

(0)
(0)
   
举报
评论 一句话评论(0
0条  
登录后才能评论!
© 2014 bubuko.com 版权所有 鲁ICP备09046678号-4
打开技术之扣,分享程序人生!
             

鲁公网安备 37021202000002号