//单词拆分
//描述:给定一个非空字符串 s 和一个包含非空单词的列表 wordDict,
// 判定 s 是否可以被空格拆分为一个或多个在字典中出现的单词。
//cpp
#include <iostream>
#include <string>
#include <vector>
#include <unordered_set>
#include<sstream>
using namespace std;
//dp[i] 表示字符串 s 的前 i 个字符能否被拆分成字典中的单词。
bool wordBreak(string s, vector<string>& wordDict) {
unordered_set<string> dict(wordDict.begin(), wordDict.end());
int n = s.size();
vector<bool> dp(n + 1, false);
dp[0] = true; // 空字符串可以被拆分
for (int i = 1; i <= n; ++i) {
for (int j = 0; j < i; ++j) {
if (dp[j] && dict.count(s.substr(j, i - j))) {
dp[i] = true;
break;
}
}
}
return dp[n];
}
int main() {
string s = "leetcode";
vector<string> wordDict = { "leet", "code" };
bool canBreak = wordBreak(s, wordDict);
if (canBreak) {
cout << "字符串可以被拆分成字典中的单词。" << endl;
}
else {
cout << "字符串无法被拆分成字典中的单词。" << endl;
}
return 0;
}
//当i=4,j=0,可以得到dp[4]=true; 当i=8时,j=4,因为dp[4]=true;s.substr(4,4)存在, 所以dp[8]为true; 最终返回dp[8]
这篇文章介绍了一个C++函数`wordBreak`,用于判断给定字符串`s`是否可以通过将字典`wordDict`中的单词重新排列组合来构成。使用动态规划方法,通过检查子串是否在字典中来决定整个字符串的拆分可行性。
1854

被折叠的 条评论
为什么被折叠?



