[Leetcode] 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".

动规实在是太强大了!注意在枚举子串长度时,只要枚举从dict字典中最短单词到最长单词的长度就可以了。

 1 class Solution {

 2 public:

 3     /**

 4      * @param s: A string s

 5      * @param dict: A dictionary of words dict

 6      */

 7     bool wordBreak(string s, unordered_set<string> &dict) {

 8         // write your code here

 9         vector<bool> dp(s.length() + 1, false);

10         dp[0] = true;

11         int min_len = INT_MAX, max_len = INT_MIN;

12         for (auto &ss : dict) {

13             min_len = min(min_len, (int)ss.length());

14             max_len = max(max_len, (int)ss.length());

15         }

16         for (int i = 0; i < s.length(); ++i) if(dp[i]) {

17             for (int len = min_len; i + len <= s.length() && len <= max_len; ++len) {

18                 if (dict.find(s.substr(i, len)) != dict.end()) 

19                     dp[i + len] = true;

20             }

21             if (dp[s.length()]) return true;

22         }

23         return dp[s.length()];

24     }

25 };

再看个非动规的版本:

 1 class Solution {

 2 public:

 3   bool wordBreakHelper(string s,unordered_set<string> &dict,set<string> &unmatched,int mn,int mx) {  

 4         if(s.size() < 1) return true;  

 5         int i = mx < s.length() ? mx : s.length();  

 6         for(; i >= mn ; i--)  

 7         {  

 8             string preffixstr = s.substr(0,i);  

 9             if(dict.find(preffixstr) != dict.end()){  

10                 string suffixstr = s.substr(i);  

11                 if(unmatched.find(suffixstr) != unmatched.end())  

12                     continue;  

13                 else  

14                     if(wordBreakHelper(suffixstr, dict, unmatched,mn,mx))  

15                         return true;  

16                     else  

17                         unmatched.insert(suffixstr);  

18             }  

19         }  

20         return false;  

21     }  

22     bool wordBreak(string s, unordered_set<string> &dict) {  

23         // Note: The Solution object is instantiated only once.  

24         if(s.length() < 1) return true;  

25         if(dict.empty()) return false;  

26         unordered_set<string>::iterator it = dict.begin();  

27         int maxlen=(*it).length(), minlen=(*it).length();  

28         for(it++; it != dict.end(); it++)  

29             if((*it).length() > maxlen)  

30                 maxlen = (*it).length();  

31             else if((*it).length() < minlen)  

32                 minlen = (*it).length();  

33         set<string> unmatched;  

34         return wordBreakHelper(s,dict,unmatched,minlen,maxlen);  

35     }

36 };

 

你可能感兴趣的:(LeetCode)