-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay10.cpp
More file actions
73 lines (60 loc) · 1.9 KB
/
Day10.cpp
File metadata and controls
73 lines (60 loc) · 1.9 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
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
/*
This problem was asked by Microsoft.
Given a dictionary of words and a string made up of those words (no spaces), return the original sentence in a list. If there is more than one possible reconstruction, return any of them. If there is no possible reconstruction, then return null.
For example, given the set of words 'quick', 'brown', 'the', 'fox', and the string "thequickbrownfox", you should return ['the', 'quick', 'brown', 'fox'].
Given the set of words 'bed', 'bath', 'bedbath', 'and', 'beyond', and the string "bedbathandbeyond", return either ['bed', 'bath', 'and', 'beyond] or ['bedbath', 'and', 'beyond'].
*/
#include <bits/stdc++.h>
using namespace std;
vector<string> wordBreak(vector<string> &words, string s)
{
unordered_set<string> wordSet(words.begin(), words.end());
vector<string> result;
int n = s.size();
vector<bool> dp(n + 1, false);
dp[0] = true;
for (int i = 1; i <= n; ++i)
{
for (int j = 0; j < i; ++j)
{
if (dp[j] && wordSet.count(s.substr(j, i - j)))
{
dp[i] = true;
break;
}
}
}
if (!dp[n])
return result;
int end = n;
for (int i = n - 1; i >= 0; --i)
{
if (dp[i] && wordSet.count(s.substr(i, end - i)))
{
result.push_back(s.substr(i, end - i));
end = i;
}
}
reverse(result.begin(), result.end());
return result;
}
int main()
{
vector<string> words = {"quick", "brown", "the", "fox"};
string s = "thequickbrownfox";
vector<string> result = wordBreak(words, s);
for (string word : result)
{
cout << word << " ";
}
cout << endl;
words = {"bed", "bath", "bedbath", "and", "beyond"};
s = "bedbathandbeyond";
result = wordBreak(words, s);
for (string word : result)
{
cout << word << " ";
}
cout << endl;
return 0;
}