-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcanConstruct.cpp
More file actions
67 lines (67 loc) · 1.73 KB
/
canConstruct.cpp
File metadata and controls
67 lines (67 loc) · 1.73 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
#include<iostream>
#include <map>
using namespace std;
// Time Complexity is O(n*m^2) And Space Complexity is O(m).
bool canConstruct(string *ar,int n,const string& str,map<string,bool> &mp){
if (str.empty()){
return true;
}
if (mp.count(str)!=0){
return mp[str];
}
for (int i = 0; i < n; ++i) {
string res = str.substr(0,ar[i].length());
if (res==ar[i]) {
if (canConstruct(ar,n,str.substr(ar[i].length()),mp)){
mp[str] = true;
return mp[str];
}
}
}
mp[str] = false;
return mp[str];
}
// Time Complexity is O(n*m^2) And Space Complexity is O(m).
bool canConstruct2(string *ar,int n,const string& str){
bool dp[str.length()+1];
for (int i = 0; i <= str.length(); ++i) {
dp[i] = false;
}
dp[0] = true;
for (int i = 1; i <=str.length(); ++i) {
if (!dp[i]){
for (int j = 0; j < n; ++j) {
if (i>=ar[j].length() && str.substr(i-ar[j].length(),ar[j].length())==ar[j] && dp[i-ar[j].length()]){
dp[i] = true;
}
}
}
}
return dp[str.length()];
}
int main(){
cout<<"Enter The value of n:\n";
int n;
cin>>n;
cout<<"Enter The value of array:\n";
auto *ar = new string [n];
for (int i = 0; i < n; ++i) {
cin>>ar[i];
}
cout<<"Enter The Target String:\n";
string str;
cin>>str;
map<string ,bool> mp;
cout<<"Using Top Down Approach:\n";
if (canConstruct(ar,n,str,mp)) {
cout << "YES";
} else{
cout<<"NO";
}
cout<<"\nUsing Bottom Up Approach:\n";
if (canConstruct2(ar,n,str)) {
cout << "YES";
} else{
cout<<"NO";
}
}