-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathword_segmentation.cpp
More file actions
46 lines (42 loc) · 1.3 KB
/
Copy pathword_segmentation.cpp
File metadata and controls
46 lines (42 loc) · 1.3 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
45
46
class Solution {
public:
/**
* @param s: A string s
* @param dict: A dictionary of words dict
*/
bool wordSegmentation(string s, unordered_set<string> &dict) {
// write your code here
// f[i] whether first i elmenets of s can be divided into words of dict
// f[0][j] = false; f[i][0] = false
// f[i] = f[i - 1] if A[i - 1] in dict
int len = s.size();
if (len == 0) {
return true;
}
bool chs[256] = {false};
for (unordered_set<string>::iterator it=dict.begin(); \
it!=dict.end(); ++it) {
string word = *it;
for (size_t i=0; i<word.size(); ++i) {
chs[static_cast<int>(word[i])] = true;
}
}
for (size_t i=0; i<s.size(); ++i) {
if (!chs[static_cast<int>(s[i])]) {
return false;
}
}
vector<bool> f(len + 1, false);
f[0] = true;
for (int i = 1 ; i < len + 1; i++) {
for (int j = 1; j <= i; j++) {
bool temp = f[i - j];
if (temp && dict.find(s.substr(i - j, j)) != dict.end()) {
f[i] = true;
break;
}
}
}
return f[len];
}
};