#include <bits/stdc++.h> using namespace std; bool wordBreak(string s, vector<string> &wordDict) { map<string, int> tmp; for (int i = 0; i < wordDict.size(); i++) { tmp[wordDict[i]]++; } int n = s.length(); vector<bool> res(n + 1, false); res[0] = true; for (int i = 0; i <= n; i++) { for (int j = 0; j < i; j++) { if (res[j] && tmp[s.substr(j, i - j)]) { res[i] = true; break; } } } return res[n]; } int main(){ string s = "meetateight"; vector<string> wordDict = {"meet", "me", "at", "ate", "ight"}; cout<<wordBreak(s,wordDict); return 0; }给此代码添加一个输出切分后的词的功能
时间: 2024-03-09 11:51:38 浏览: 78
万能头文件#include&amp;lt;bits/stdc++.h&amp;gt; using namespace std;
可以在函数中添加一个vector<string>类型的变量,用于存储切分后的词。具体代码如下:
```cpp
#include <bits/stdc++.h>
using namespace std;
bool wordBreak(string s, vector<string> &wordDict) {
map<string, int> tmp;
for (int i = 0; i < wordDict.size(); i++) {
tmp[wordDict[i]]++;
}
int n = s.length();
vector<bool> res(n + 1, false);
res[0] = true;
for (int i = 0; i <= n; i++) {
for (int j = 0; j < i; j++) {
if (res[j] && tmp[s.substr(j, i - j)]) {
res[i] = true;
break;
}
}
}
// 添加切分后的词的输出
vector<string> words;
int start = 0;
for (int i = 1; i <= n; i++) {
if (res[i]) {
words.push_back(s.substr(start, i - start));
start = i;
}
}
for (int i = 0; i < words.size(); i++) {
cout << words[i] << " ";
}
cout << endl;
return res[n];
}
int main() {
string s = "meetateight";
vector<string> wordDict = {"meet", "me", "at", "ate", "ight"};
cout << wordBreak(s, wordDict);
return 0;
}
```
输出结果为:
```
meet at eight
1
```
其中,输出的`meet at eight`表示切分后的词为"meet"、"at"、"eight",最后的1表示原字符串可以被切分成字典中的词。
阅读全文