-
Notifications
You must be signed in to change notification settings - Fork 0
/
139. Word Break.cpp
83 lines (81 loc) · 1.71 KB
/
139. Word Break.cpp
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/*
#include <string>
#include <vector>
using namespace std;
class Solution
{
public:
bool wordBreak(const string s, vector<string> &wordDict)
{
str = s;
n = s.size();
memo = vector<int>(n, 0);
return dfs(wordDict, 0) == 1;
}
private:
int n;
vector<int> memo;
string str;
int dfs(vector<string> &word, int idx)
{
if (idx == n)
return 1;
if (memo[idx] != 0)
return memo[idx];
int r = -1;
for (auto &w : word)
{
if (r == 1)
break;
if (w.size() + idx <= n)
{
int i = idx;
while (str[i] == w[i - idx] && i < w.size() + idx)
i++;
if (i == w.size() + idx)
r = dfs(word, i) == 1;
}
}
return memo[idx] = (r == 1 ? 1 : -1);
}
};
*/
#include <string>
#include <vector>
#include <bitset>
using namespace std;
class Solution
{
public:
bool wordBreak(const string s, vector<string> &wordDict)
{
const int n = s.size();
bitset<301> dp;
str = s;
dp[n] = true;
for (int i = n - 1; i >= 0; i--)
{
for (auto &w : wordDict)
{
if (check(w, i))
dp[i] = dp[i + w.size()];
if (dp[i])
break;
}
}
return dp[0];
}
private:
string str;
bool check(string w, int i)
{
int j = i + w.size() - 1;
if (j >= str.size())
return false;
int s;
for (s = i; str[s] == w[s - i] && s <= j; s++)
{
}
return s == j + 1;
}
};