Level:

  Medium

题目描述:

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

思路分析:

  题目要求判断给出的字符串是否能由词典中的单词组成,我们应该用动态规划的思想去解决。但凡是能把问题规模缩小的都应该想到用动态规划求解。例如本题,如果我知道给定字符串的0到i子串可以用字典中的单词表达,那么我只需要知道i+1到末尾的子串能否被字典表达即可知道整个字符串能否被字典表达。所以随着i的增大,问题规模逐渐的缩小,且之前求解过的结果可以为接下来的求解提供帮助,这就是动态规划了。设dp[i]代表s.substring(0, i)能否被字典表达,此刻我们知道dp[0]~dp[i-1]的结果。而dp[i]的结果由两部分组成,一部分是dp[j](j < i),已知;另一部分是j到i之间的字符串是不是在字典里。当这两个部分都为真的时候,dp[i]即为真。而一旦dp[i]为真,就不用继续迭代了。测试的时候发现倒着遍历会比正着遍历速度稍稍快一点,大概是因为test case的字典里长度较长的单词要比长度较短的单词多。

代码:

public class Solution{
public boolean wordBreak(String s,List<String>wordDict){
if(s==null||s.length()==0)
return false;
boolean []dp=new boolean [s.length()+1]; //dp[i]表示字符串的前i个字符是否能由词典中的单词表示。
dp[0]=true;
for(int i=1;i<=s.length();i++){
for(int j=0;j<i;j++){
if(dp[j]&&wordDict.contains(s.substring(j,i))){
dp[i]=true;
break;
}
}
}
return dp[s.length()];
}
}

最新文章

  1. c#.net WinForm 线程内 调用窗体控件
  2. Tomcat 7 Connector 精读(1)
  3. 3D Touch的简单使用
  4. input hidden用法
  5. SSH是什么?Linux如何修改SSH端口号?
  6. 慎重使用MySQL auto_increment
  7. jquery自己主动旋转的登录界面的背景代码登录页背景图
  8. 三分钟跑起jsblocks
  9. NHibernate的常见问题及解决方案
  10. Centos7 安装 jdk 1.8
  11. Django--缓存设置
  12. jqGrid 刷新单行数据
  13. HDMI ip中的时钟 vid_clk与ls_clk
  14. 企业项目开发--cookie(2)
  15. 第16章 STM32中断应用概览
  16. 树莓派系统(Debain)中设置SSH服务开机自启动
  17. mysql 查询每秒写入数据库的记录数
  18. hdu 4417 Super Mario 树状数组||主席树
  19. OpenCV尺寸调整
  20. SourceTree代码管理学习git命令操作

热门文章

  1. CSS-02 BFC的理解
  2. swagger集成到springBoot 项目中
  3. git兼容svn与hg功能
  4. 外包项目测试工作量评估指南&amp;外包项目测试验收流程
  5. 回顾Servlet及SpringMVC
  6. AcWing 244. 谜一样的牛 (树状数组+二分)打卡
  7. [杂题]:staGame(博弈论+Trie树+DFS)
  8. Ubuntu编译ruby
  9. Mac上VMWare Fusion配置多台cent os
  10. PHP缓存技术OB系统函数(总结)