-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path139. Word Break.cpp
80 lines (50 loc) · 1.51 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
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
unordered_map<string, int> m;
for(auto words: wordDict)
m[words]++;
if (wordDict.empty() || s.empty())
return false;
if (m[s])
return true;
int n = s.length();
vector<int> v(n, 0);
for (int i = 0; i< n; ++i) {
string word = s.substr(0,i+1);
if (m[word] || v[i]) {
v[i] = 1;
for(int j = i+1; j<n; ++j) {
string rightword = s.substr(i+1, j-i);
if (m[rightword] || v[j]) {
if (j == n-1)
return true;
v[j] = 1;
}
}
}
}
return v[n-1] == 1;
}
};
--------
// Brute force recursive solution. Gets TLE. Nice use of recursion though.
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
if (wordDict.empty() || s.empty())
return false;
int n = s.length()-1;
for (int i = 1; i<= s.length(); ++i) {
string str = s.substr(0, i);
if (find(wordDict.begin(), wordDict.end(), str) != wordDict.end()) {
if (str == s)
return true;
if (wordBreak(s.substr(i,n-i+1), wordDict)) {
return true;
}
}
}
return false;
}
};