Word Break

Word Break


Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.

For example, given

s = “leetcode”,

dict = [“leet”, “code”].

Return true because “leetcode” can be segmented as “leet code”.

呃……DP?

感觉代码写的挺不好的……

AC代码:

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
class Solution {
public:
vector<vector<int>> DP;
bool solve(int begin, int end, string& s, unordered_set<string>& wordDict)
{

if (begin > end) return false;
if (DP[begin][end] == 1) return true;
else if (DP[begin][end] == 2) return false;
if (begin == end)
{
string str;
str.push_back(s[begin]);
if (wordDict.find(str) != wordDict.end())
{
DP[begin][end] = 1; return true;
}
else
{
DP[begin][end] = 2; return false;
}
}
else if (begin > end)
{
DP[begin][end] = 2;
return false;
}
else
{
string str;
for (int i = begin; i <= end; ++i)
{
str.push_back(s[i]);
}
if (wordDict.find(str) != wordDict.end())
{
DP[begin][end] = 1; return true;
}

for (int i = begin; i <= end; ++i)
{
bool l = solve(begin, i, s, wordDict);
bool r = solve(i+1, end, s, wordDict);
if (l && r)
{
DP[begin][end] = 1; return true;
}
else
{
if (0 == DP[begin][end])
{ DP[begin][end] = 2; }
}
}
}
DP[begin][end] = 2;
return false;
}

bool wordBreak(string s, unordered_set<string>& wordDict) {
DP = vector<vector<int>>(s.length(),vector<int>(s.length(),0));
return solve(0, s.length()-1, s, wordDict);
}
};