【29】139. Word Break

139. Word Break

  • Total Accepted: 127484
  • Total Submissions: 447287
  • Difficulty: Medium
  • Contributors: Admin

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. You may assume the dictionary does not contain duplicate words.

For example, given
s = "leetcode",
dict = ["leet", "code"].

Return true because "leetcode" can be segmented as "leet code".

UPDATE (2017/1/4):
The wordDict parameter had been changed to a list of strings (instead of a set of strings). Please reload the code definition to get the latest changes.

 1 class Solution {
 2 public:
 3 //DP
 4     bool wordBreak(string s, vector<string>& wordDict) {
 5         int n = s.size();
 6         unordered_set<string> dict;
 7         for(string ss : wordDict){
 8             dict.insert(ss);
 9         }
10         vector<bool> dp(n + 1, false);
11         dp[0] = true;//s为空的时候是true
12         for(int i = 1; i < n + 1; i++){
13             for(int j = 0; j < i; j++){
14                 if(dp[j] && dict.find(s.substr(j, i - j)) != dict.end()){//vector没有find方法,用set
15                     dp[i] = true;
16                     break;//只要找到一种解法 到第i个char时可以分解 就break
17                 }
18                 
19             }
20         }
21         return dp[n];
22     }
23 };

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

posted @ 2017-02-08 08:07  会咬人的兔子  阅读(168)  评论(0编辑  收藏  举报