-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWord_Break_Problem_topdown.cpp
More file actions
90 lines (76 loc) · 2.09 KB
/
Word_Break_Problem_topdown.cpp
File metadata and controls
90 lines (76 loc) · 2.09 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include<iostream>
#include<string.h>
#include<set>
#include<map>
#include <chrono>
using namespace std::chrono;
using namespace std;
bool check_key(map<string, bool> m,string key)
{
if (m.find(key) == m.end())
return false;
return true;
}
bool match(string s,string dictionary[],int l)
{
for(int i=0;i<l;i++){
if(s==dictionary[i]){
return true;
}
}
return false;
}
bool match_strings(string s,map<string,bool> &m,string dictionary[],int l){
if(s.empty()){
return true;
}
if(check_key(m,s)){
auto itr = m.find(s);
return itr->second;
}
for(int i=1;i<=s.length();i++){
bool ans =match_strings(s.substr(i,s.length()-i+1),m,dictionary,l);
if(match(s.substr(0,i),dictionary,l) && ans){
m.insert({s.substr(i,s.length()-i+1),true});
return true;
}else{
if(ans){
m.insert({s.substr(i,s.length()-i+1),true});
}else{
m.insert({s.substr(i,s.length()-i+1),false});
}
}
}
return false;
}
bool repeat(string s,string dictionary[],int l)
{
map<string,bool> m;
if(match_strings(s,m,dictionary,l)){
return true;
}
return false;
}
int main(){
int n;
cout<<"Enter the length of dictionary: ";
cin>>n;
cout<<"\nEnter the words of dictionary: ";
string dictionary[n];
for(int i=0;i<n;i++){
cin>>dictionary[i];
}
cout<<"\nEnter the string: ";
string s;
cin>>s;
auto start = high_resolution_clock::now();
if(repeat(s,dictionary,n)){
cout<<"****String can be segmented into a space-separated sequence of dictionary words.****"<<endl;
}else{
cout<<"****String can *NOT* be segmented into a space-separated sequence of dictionary words.****"<<endl;
}
auto stop = high_resolution_clock::now();
cout <<endl<< "Time taken by string segment check in microseconds : "
<< chrono::duration_cast<chrono::microseconds>(stop - start).count()<< " microseconds" << endl;
return 0;
}