-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path120WordBreak.cpp
More file actions
44 lines (35 loc) · 1.02 KB
/
Copy path120WordBreak.cpp
File metadata and controls
44 lines (35 loc) · 1.02 KB
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include<iostream>
#include<vector>
#include<unordered_set>
using namespace std;
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
unordered_set<string> str(wordDict.begin(), wordDict.end());
int n = (int)s.size();
vector<bool>dp(n + 1, false);
dp[0] = true;
int maxLen = 0;
for(auto &w : wordDict) maxLen = max((int)w.size(), maxLen);
for(int i = 1; i <= n; i++){
for(int len = 1; len <= maxLen && len <= i; len++){
int j = i - len;
if(!dp[j]) continue;
if(str.find(s.substr(j, len)) != str.end()){
dp[i] = true;
break;
}
}
}
return dp[n];
}
};
int main(){
Solution obj;
string s = "leetcode";
vector<string> wordDict = {"leet", "code"};
bool result = obj.wordBreak(s, wordDict);
cout << "Can be segmented? ";
cout << (result ? "True" : "False") << endl;
return 0;
}