140. 单词拆分 II

2023-05-13,,

Q:

给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,在字符串中增加空格来构建一个句子,使得句子中所有的单词都在词典中。返回所有这些可能的句子。

说明:

分隔时可以重复使用字典中的单词。
你可以假设字典中没有重复的单词。
示例 1:

输入:
s = “catsanddog”
wordDict = [“cat”, “cats”, “and”, “sand”, “dog”]
输出:
[
“cats and dog”,
“cat sand dog”
]
示例 2:

输入:
s = “pineapplepenapple”
wordDict = [“apple”, “pen”, “applepen”, “pine”, “pineapple”]
输出:
[
“pine apple pen apple”,
“pineapple pen apple”,
“pine applepen apple”
]
解释: 注意你可以重复使用字典中的单词。
示例 3:

输入:
s = “catsandog”
wordDict = [“cats”, “dog”, “sand”, “and”, “cat”]
输出:
[]

A:

关键是要先用139的代码算一下给的字符串能不能被拆分为字典里的单词,不能直接返回。因为算是否能被拆分是O(N ^ 2),而本题要求的所有序列是O(N ^ 3),不先判断一下有一个全是’a’的用例是过不去的。。

C++:

 class Solution {
public:
vector<string> wordBreak(string s, vector<string>& wordDict) {
vector<vector<string>> dp(s.size(),vector<string>());
unordered_set<string> dic;
for(auto& str:wordDict){
dic.insert(str);
}
vector<bool> judge(s.size(),false);
for(int i=0;i<s.size();++i){
if(dic.count(s.substr(0,i+1))){judge[i]=true;}
else{
for(int j=0;j<=i;++j){
if(judge[j] and dic.count(s.substr(j+1,i-j))){
judge[i]=true;
break;
}
}
}
}
if(not judge.back()){return {};}
//dp[i]表示s截止到i的可能分割出的句子
for(int i=0;i<s.size();++i){
for(int j=0;j<=i;++j){
if(dic.count(s.substr(j,i-j+1))){
string str2=s.substr(j,i-j+1);
if(j==0){
dp[i].push_back(str2);
continue;
}
if(not judge[j-1]){continue;}
for(auto& str1:dp[j-1]){
dp[i].push_back(str1+" "+str2);
}
}
}
}
return dp[s.size()-1];
}
};

python:

 class Solution:
def wordBreak(self, s: str, WordDict):
l=len(s)
if not l:
return 0
dic={ x:1 for x in WordDict}
#上一题代码拿来用
judge=[0 for i in range(l)]
judge[0]=int(s[0] in dic) #i==0递推基础
for i in range(1,l): #i==1开始遍历
if s[:i+1] in dic:
judge[i]=1
else:
for j in range(i):
if judge[j] and s[j+1:i+1] in dic:
judge[i]=1
break
print(judge)
if not judge[-1]:
return []
#开始算本题所求的序列
dp=[[]for i in range(l)] #dp[i]是一个列表,存储不同的s[1,i]闭区间的有效拆分序列
if s[0] in dic:
dp[0].append(s[0]) #递推起始状态
for i in range(1,l): #从i==1开始自底向上递推
if s[:i+1] in dic: #s[0:i+1]本身就在字典里则加入解集
dp[i].append(s[:i+1])
for cut in range(i): #进行切分,符合条件的加入解集
if s[cut+1:i+1] in dic and judge[cut]:
#cut前面的子问题有解且cut之后到i的字符串在字典中
for x in dp[cut]: #x为字符串
dp[i].append(x+' '+s[cut+1:i+1])
#把dp[cut]中的每个解加上cut后的字符串,插入dp[i]的解集
# print(dp)
return dp[-1]

140. 单词拆分 II的相关教程结束。

《140. 单词拆分 II.doc》

下载本文的Word格式文档,以方便收藏与打印。