-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwordsep.cpp
More file actions
29 lines (27 loc) · 956 Bytes
/
wordsep.cpp
File metadata and controls
29 lines (27 loc) · 956 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/*s 和多个单词组成的WordDict
判断是否可以由WordDict中的一个或多个单词构成*/
#include <iostream>
#include <string>
#include <vector>
#include <unordered_set>
using namespace std;
bool wordBreak(string s, vector<string>& wordDict) {
unordered_set<string> dict(wordDict.begin(), wordDict.end());
vector<bool> dp(s.size() + 1, false);
dp[0] = true;
for (int i = 1; i <= s.size(); i++) {
for (int j = 0; j < i; j++) {
if (dp[j] && dict.count(s.substr(j, i - j))) { // j之前的字符串可以由wordDict中的单词组成,且j到i之间的字符串是wordDict中的单词
dp[i] = true; // i之前的字符串可以由wordDict中的单词组成
break;
}
}
}
return dp[s.size()];
}
int main() {
string s = "threedogs";
vector<string> wordDict = {"three", "dog", "s"};
cout << wordBreak(s, wordDict) << endl;
return 0;
}