43.Word Break(看字符串是否由词典中的单词组成)
2024-09-03 17:07:22
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()];
}
}
最新文章
- c#.net WinForm 线程内 调用窗体控件
- Tomcat 7 Connector 精读(1)
- 3D Touch的简单使用
- input hidden用法
- SSH是什么?Linux如何修改SSH端口号?
- 慎重使用MySQL auto_increment
- jquery自己主动旋转的登录界面的背景代码登录页背景图
- 三分钟跑起jsblocks
- NHibernate的常见问题及解决方案
- Centos7 安装 jdk 1.8
- Django--缓存设置
- jqGrid 刷新单行数据
- HDMI ip中的时钟 vid_clk与ls_clk
- 企业项目开发--cookie(2)
- 第16章 STM32中断应用概览
- 树莓派系统(Debain)中设置SSH服务开机自启动
- mysql 查询每秒写入数据库的记录数
- hdu 4417 Super Mario 树状数组||主席树
- OpenCV尺寸调整
- SourceTree代码管理学习git命令操作