forked from priyanshu-bhatt/Hactoberfest2021
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwordbreak_backtracking.cpp
More file actions
71 lines (57 loc) · 1.63 KB
/
wordbreak_backtracking.cpp
File metadata and controls
71 lines (57 loc) · 1.63 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
/*
Author: Kinjal Kumari
Github: @cutiecoder
Event: Hactober Fest 2021
Given a string s and a dictionary of words dict of length n, add spaces in s to construct a sentence where each word is a valid dictionary word. Each dictionary word can be used more than once. Return all such possible sentences.
We have to complete the function wordBreak() which takes n, dict and s as input parameters and returns a list of possible sentences. If no sentence is possible it returns an empty list.
Expected Time Complexity: O(N2*n) where N = |s|
Expected Auxiliary Space: O(N2)
Constraints:
1 ≤ n ≤ 20
1 ≤ dict[i] ≤ 15
1 ≤ |s| ≤ 500
*/
#include <iostream>
using namespace std;
int dictionaryContains(string &word)
{
string dictionary[] = {"mobile","samsung","sam","sung",
"man","mango", "icecream","and",
"go","i","love","ice","cream"};
int n = sizeof(dictionary)/sizeof(dictionary[0]);
for (int i = 0; i < n; i++)
if (dictionary[i].compare(word) == 0)
return true;
return false;
}
void wordBreakUtil(string str, int size, string result);
void wordBreak(string str)
{
wordBreakUtil(str, str.size(), "");
}
void wordBreakUtil(string str, int n, string result)
{
for (int i=1; i<=n; i++)
{
string prefix = str.substr(0, i);
if (dictionaryContains(prefix))
{
if (i == n)
{
result += prefix;
cout << result << endl;
return;
}
wordBreakUtil(str.substr(i, n-i), n-i,
result + prefix + " ");
}
}
}
int main()
{
cout << "First Test:\n";
wordBreak("iloveicecreamandmango");
cout << "\nSecond Test:\n";
wordBreak("ilovesamsungmobile");
return 0;
}