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".

Analyse: Difine dp[i] is whether S[0...i] can be segmented, thus dp[i] is true means that s[0,...k], s[k + 1, ....i] can be segmented, where 0 < k < i. 

dp[i] = dp[k] && wordDict.find(s.substr(k + 1, i - k)) != wordDict.end(). 

Runtime: 16ms.

 1 class Solution {
 2 public:
 3     bool wordBreak(string s, unordered_set<string>& wordDict) {
 4         string newstr = "#" + s;
 5         int len = newstr.size();
 6         vector<bool> dp(len, false);
 7         
 8         dp[0] = true;
 9         for(int i = 1; i < len; i++){
10             for(int k = 0; k < i; k++){
11                 dp[i] = dp[k] && wordDict.find(newstr.substr(k + 1, i - k)) != wordDict.end();
12                 if(dp[i]) break; //s[0...i] can be segmented
13             }
14         }
15         return dp[len - 1];
16     }
17 };
原文地址:https://www.cnblogs.com/amazingzoe/p/4753438.html