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

 题意:S是否可以由dict中的字符串合成。

思路:动态规划。维护一个数组vector<bool> dp(s.size()+1,false),其中dp[i] 代表S中[0,i-1]是否用dict中的字符串表示,能,true,不能,false。对dp[i]而言,若dp[j] (j<i)能在dict中找到,则只需看s.substr(j,i-j)是否能在dict中找到,若能,则i++,重新分析,不能j++。这里值得注意的是:下标的问题。dp[j]表示S中s.substr(0,j)(前闭后开,所以代表S中[0, j-1] 子字符串 )能否在dict中找到。代码如下:

 1 class Solution {
 2 public:
 3     bool wordBreak(string s, unordered_set<string> &dict) 
 4     {
 5         int len=s.size();
 6         vector<bool> dp(len+1,false);
 7         dp[0]=true;    /
 8 
 9         for(int i=0;i<len+1;++i)
10         {
11             for(int j=0;j<i;++j)
12             {
13                 if(dp[j]&&dict.find(s.substr(j,i-j)) !=dict.end())
14                 {
15                     dp[i]=true;
16                     break;
17                 }
18             }
19         }
20         return res[len];
21     }
22 };

 

网友Code Gander 总结了动态规划的一般套路。 

个人总结:

动态规划:基于一个递推公式以及一个或者多个初始状态。较为重要是:状态和状态转移方程!

三步曲:

一、存储什么历史信息以及用什么结构;
二、递推方程(重要);

三、起始条件;

最重要的还是知道,什么情况下用动态规划。

posted @ 2017-07-04 18:27  王大咩的图书馆  阅读(207)  评论(0编辑  收藏  举报