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 Solution:
  使用动态规划进行求解
  这道题其实还是一道经典的 DP 题目,也就是动态规划 Dynamic Programming。博主曾经说玩子数组或者子字符串且求极值的题,基本就是 DP 没差了,虽然这道题没有求极值,但是玩子字符串也符合 DP 的状态转移的特点。把一个人的温暖转移到另一个人的胸膛... 咳咳,跑错片场了,那是爱情转移~ 强行拉回,DP 解法的两大难点,定义 dp 数组跟找出状态转移方程,先来看 dp 数组的定义,这里我们就用一个一维的 dp 数组,其中 dp[i] 表示范围 [0, i) 内的子串是否可以拆分,注意这里 dp 数组的长度比s串的长度大1,是因为我们要 handle 空串的情况,我们初始化 dp[0] 为 true,然后开始遍历。注意这里我们需要两个 for 循环来遍历,因为此时已经没有递归函数了,所以我们必须要遍历所有的子串,我们用j把 [0, i) 范围内的子串分为了两部分,[0, j) 和 [j, i),其中范围 [0, j) 就是 dp[j],范围 [j, i) 就是 s.substr(j, i-j),其中 dp[j] 是之前的状态,我们已经算出来了,可以直接取,只需要在字典中查找 s.substr(j, i-j) 是否存在了,如果二者均为 true,将 dp[i] 赋为 true,并且 break 掉,此时就不需要再用j去分 [0, i) 范围了,因为 [0, i) 范围已经可以拆分了。最终我们返回 dp 数组的最后一个值,就是整个数组是否可以拆分的布尔值了,代码如下:
 class Solution {
public:
bool wordBreak(string s, unordered_set<string> &dict) {
vector<string> wordDict;
unordered_set<string>dict;
for (auto a : wordDict)
dict.insert(a);
vector<bool>dp(s.size() + , false);
dp[] = true;//边界
for(int i=;i<dp.size();++i)
for(int j=;j<i;++j)
if (dp[j] && dict.count(s.substr(j, i - j)))//状态转移方程
{
dp[i] = true;
break;
}
return dp.back();
}
};

最新文章

  1. vsftpd安装配置 530 Permission denied.错误
  2. 【Git学习笔记】撤销修改
  3. js控制 固定框架内图片 按比例显示 以及 占满框架 居中显示
  4. 11个很棒的 jQuery 图表库
  5. Amoeba-mysql读写分离实战
  6. Apache Spark源码走读之1 -- Spark论文阅读笔记
  7. 活动组件(五):一个activity的例子
  8. SQL备份(全)
  9. Linux 文件/文件夹操作命令
  10. Resharper
  11. Unity3D 游戏开发构架篇 ——输入控制
  12. shell随机生成身份证,姓名,电话,日期,分数,等级和insert语句
  13. [20190401]跟踪dbms_lock.sleep调用.txt
  14. Asp.net MVC WebApi项目的自动接口文档及测试功能打开方法
  15. linux 7安装telnet,设置telnet自启动,使用root telnet登录
  16. Android-Version Compatibility Issues (Gradle 2.14.1 requires Android Gradle plugin 2.1.3 (or newer)) but project is using
  17. Swift3.0:NSURLConnection的使用
  18. (GoRails)ActionCable如何用Redis + 菜鸟redis教程
  19. Fastboot和Recovery
  20. XHTML1.0版本你知道么,跟html5版本有什么区别

热门文章

  1. Vue2.0---webpack打包知识点-1
  2. urllib库爬取实例
  3. app自动化生成测试报告
  4. 创建网关项目(Spring Cloud Gateway)
  5. 53-python基础-python3-列表-列表解析
  6. Educational Codeforces Round 33 D. Credit Card
  7. go语言从例子开始之Example8.数组
  8. 联想think system sr550信息
  9. windows7下搭建robot framework环境
  10. oracle exp不生成dumpfile,预估出实际导出文件的大小。