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

给一个字符串,看是否可以由字典中的单词拆分成以空格隔开的单词序列。

用动态规划DP来解,某一个字符前面的字符串的拆分方法可能有多种,后面的拆分要看前面的拆分组合。

State: dp[i],  表示到字符i时,前面1~i的字符串能否拆分

Function: dp[i] = (dp[i - j] + str[j:i] in dict) for j in range(i), 到字符i能否拆分取决于每一个以i结尾的str[j-i]字符 是否在字典里并且j字符之前的字符串可以拆分

Initialize: dp[0] = true

Return: dp[n], 到最后一个字符n是否能拆分

在截取j 到 i 字符串,判断是否在字典中时,可以先判断字典中的字符串最大长度,超出长度就不用再循环了。

此方法可以告诉我们是否能拆分字典中的单词,但不能给出具体拆分内容。如果要知道具体拆分内容要用DFS,见140题。

Java:

public class Solution {
public boolean wordBreak(String s, Set<String> dict) {
boolean[] f = new boolean[s.length() + 1];
f[0] = true; for(int i=1; i <= s.length(); i++){
for(int j=0; j < i; j++){
if(f[j] && dict.contains(s.substring(j, i))){
f[i] = true;
break;
}
}
} return f[s.length()];
}
}

Java:

public class Solution {
public boolean wordBreak(String s, Set<String> dict) {
boolean[] f = new boolean[s.length() + 1];
f[0] = true; for(int i = 1; i <= s.length(); i++){
for(String str: dict){
if(str.length() <= i){
if(f[i - str.length()]){
if(s.substring(i-str.length(), i).equals(str)){
f[i] = true;
break;
}
}
}
}
} return f[s.length()];
}
}  

Java:

public boolean wordBreak(String s, Set<String> dict) {
if(s==null || s.length()==0)
return true;
boolean[] res = new boolean[s.length()+1];
res[0] = true;
for(int i=0;i<s.length();i++)
{
StringBuilder str = new StringBuilder(s.substring(0,i+1));
for(int j=0;j<=i;j++)
{
if(res[j] && dict.contains(str.toString()))
{
res[i+1] = true;
break;
}
str.deleteCharAt(0);
}
}
return res[s.length()];
}

Python:

class Solution(object):
def wordBreak(self, s, wordDict):
n = len(s) max_len = 0
for string in wordDict:
max_len = max(max_len, len(string)) can_break = [False for _ in xrange(n + 1)]
can_break[0] = True
for i in xrange(1, n + 1):
for j in xrange(1, min(i, max_len) + 1):
if can_break[i-j] and s[i-j:i] in wordDict:
can_break[i] = True
break return can_break[-1]

Python: wo

class Solution(object):
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: bool
"""
n = len(s)
dp = [False] * (n + 1)
dp[0] = True
for i in xrange(1, n + 1):
for j in xrange(0, i):
if dp[j] and s[j:i] in wordDict:
dp[i] = True
break return dp[-1]   

C++:

class Solution {
public:
bool wordBreak(string s, unordered_set<string>& wordDict) {
const int n = s.length(); size_t max_len = 0;
for (const auto& str: wordDict) {
max_len = max(max_len, str.length());
} vector<bool> canBreak(n + 1, false);
canBreak[0] = true;
for (int i = 1; i <= n; ++i) {
for (int l = 1; l <= max_len && i - l >= 0; ++l) {
if (canBreak[i - l] && wordDict.count(s.substr(i - l, l))) {
canBreak[i] = true;
break;
}
}
} return canBreak[n];
}
};

Followup: 返回其中的一个解,如果要返回全部解需要用140. Word Break II的方法,一个解要简单很多。F jia

Java:

class Solution {
public String wordBreak(String s, Set<String> dict) {
if (s == null || s.isEmpty() || dict == null) {
return "";
} boolean[] dp = new boolean[s.length() + 1];
String[] words = new String[s.length() + 1];
dp[0] = true;
words[0] = ""; for (int i = 1; i <= s.length(); i++) {
for (int j = 0; j < i; j++) {
if (dp[j] && dict.contains(s.substring(j, i))) {
dp[i] = true;
if (words[j].isEmpty()) {
words[i] = s.substring(j, i);
} else {
words[i] = words[j] + " " + s.substring(j, i);
}
}
}
}
if (dp[s.length()]) {
return words[s.length()];
} else {
return "";
}
} public static void main(String[] args) {
String s = new String("catsanddog");
String[] d = {"cat", "cats", "and", "sand", "dog"};
Set<String> dict = new HashSet<String>();
dict.addAll(Arrays.asList(d));
System.out.println(s);
System.out.println(dict);
Solution sol = new Solution();
System.out.println(sol.wordBreak(s, dict));
}
}

  

类似题目:

[LeetCode] 140. Word Break II 单词拆分II

[LeetCode] 97. Interleaving String 交织相错的字符串

All LeetCode Questions List 题目汇总

[LeetCode] 139. Word Break 单词拆分的更多相关文章

  1. LeetCode 139. Word Break单词拆分 (C++)

    题目: Given a non-empty string s and a dictionary wordDict containing a list of non-emptywords, determ ...

  2. [leetcode]139. Word Break单词能否拆分

    Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine ...

  3. 139 Word Break 单词拆分

    给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,确定 s 是否可以被空格分割为一个或多个在字典里出现的单词.你可以假设字典中无重复的单词.例如,给出s = "leet ...

  4. leetcode 139. Word Break 、140. Word Break II

    139. Word Break 字符串能否通过划分成词典中的一个或多个单词. 使用动态规划,dp[i]表示当前以第i个位置(在字符串中实际上是i-1)结尾的字符串能否划分成词典中的单词. j表示的是以 ...

  5. Leetcode#139 Word Break

    原题地址 与Word Break II(参见这篇文章)相比,只需要判断是否可行,不需要构造解,简单一些. 依然是动态规划. 代码: bool wordBreak(string s, unordered ...

  6. [LeetCode] 139. Word Break 拆分词句

    Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine ...

  7. Leetcode139. Word Break单词拆分

    给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,判定 s 是否可以被空格拆分为一个或多个在字典中出现的单词. 说明: 拆分时可以重复使用字典中的单词. 你可以假设字典中没有重复 ...

  8. leetcode 139. Word Break ----- java

    Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separa ...

  9. LeetCode #139. Word Break C#

    Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separa ...

随机推荐

  1. Andrew Ng机器学习 一: Linear Regression

    一:单变量线性回归(Linear regression with one variable) 背景:在某城市开办饭馆,我们有这样的数据集ex1data1.txt,第一列代表某个城市的人口,第二列代表在 ...

  2. Codeforces J. Monotonic Renumeration(组合)

    题目描述: You are given an array consisting of nmonotonic renumeration as an array b consisting of \(n\) ...

  3. 微信小程序中,如果没有参数,如何设置默认参数?

    现在学会小程序,这方面的知识,需要积累. 现在的情况是这样: 如果想从后端获取产品列表,而这些列表是可以根据分类来获取的,也是可以获取所有产品的. 那么,为了不使小程序报错,那么,我们就可以将不传的参 ...

  4. 解决Invalid character found in the request target. The valid characters are defined in RFC 7230 and RF

    通过这里的回答,我们可以知道: Tomcat在 7.0.73, 8.0.39, 8.5.7 版本后,添加了对于http头的验证. 具体来说,就是添加了些规则去限制HTTP头的规范性 参考这里 具体来说 ...

  5. java 数据库迁移工具 flyway

    官方 https://github.com/flyway/flyway 简易demo https://github.com/deadzq/flyway-demo 主要在配置文件上做改动

  6. Java-Long类型精度丢失问题

    问题 今天碰到一个问题,后端需要返回给前端Long类型的id,前端收到的id会发生精度丢失. 测试代码:后端返回的值为344739147160346624 但是前端获取的值为: 解决办法 将返回的值转 ...

  7. numpy.linalg.svd函数

    转载自:python之SVD函数介绍 函数:np.linalg.svd(a,full_matrices=1,compute_uv=1) 参数: a是一个形如\((M,N)\)的矩阵 full_matr ...

  8. Linux环境下Nexus3.6安装

    1.  安装JDK   2. 下载nexus开源版本即可,Nexus OSS下载 流程 3.  解压文件,会的得到两个文件夹[nexus-3.6.0]和[sonatype-work] tar -zxv ...

  9. Spring Cloud Feign踩坑记录(二)

    注意,以下的Feign遇到的坑,在高版本中有些已经修复. 某些项目由于历史包袱原因,无法进行全面升级,才需要修补这些坑. 1.启动报错:not annotated with HTTP method t ...

  10. HDFS练习

    利用Shell命令与HDFS进行交互 以”./bin/dfs dfs”开头的Shell命令方式 1.目录操作 在HDFS中为hadoop用户创建一个用户目录(hadoop用户) 在用户目录下创建一个i ...