-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1239. Maximum Length of a Concatenated String with Unique Characters.cpp
137 lines (115 loc) · 3.09 KB
/
1239. Maximum Length of a Concatenated String with Unique Characters.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
// RECURSION
// Time complexity - O(2^N * length of string)
// Space complexity- (N+N+N)
class Solution {
public:
int help(vector<string>& arr,int i,string temp,unordered_map<char,int>& mp,vector<int>& unique)
{
//base case
if(i==arr.size())
return temp.length();
//recursive calls
//small calculation
int a=help(arr,i+1,temp,mp,unique);
bool flag=1;
for(auto it:arr[i])
{
if(mp[it]>=1)
{
flag=0;
break;
}
}
int b=0;
if(flag and unique[i])
{
for(auto it:arr[i])
mp[it]++;
b=help(arr,i+1,temp+arr[i],mp,unique);
for(auto it:arr[i])
mp[it]--;
}
return max(a,b);
}
int maxLength(vector<string>& arr) {
vector<int> unique(arr.size(),1);
for(int i=0;i<arr.size();i++)
{
unordered_map<char,int> mp;
bool flag=1;
for(auto x:arr[i])
{
if(mp.count(x))
{
flag=0;
break;
}
mp[x]++;
}
if(flag)
unique[i]=1;
else
unique[i]=0;
}
unordered_map<char,int> mp;
string ans="";
return help(arr,0,"",mp,unique);
}
};
// Powerset
// Time complexity - O(2^N * N * length of string)
// Space complexity- (N+N)
class Solution {
public:
int maxLength(vector<string>& arr) {
vector<int> unique(arr.size(),1);
for(int i=0;i<arr.size();i++)
{
unordered_map<char,int> mp;
bool flag=1;
for(auto x:arr[i])
{
if(mp.count(x))
{
flag=0;
break;
}
mp[x]++;
}
if(flag)
unique[i]=1;
else
unique[i]=0;
}
int ans=0;
for(int i=0;i<(1<<arr.size());i++)
{
unordered_map<char,int> mp;
string temp="";
for(int j=0;j<arr.size();j++)
{
if((i&(1<<j)) and unique[j])
{
bool flag=1;
for(auto it:arr[j])
{
if(mp[it]>=1)
{
flag=0;
break;
}
}
if(flag)
{
for(auto it:arr[j])
mp[it]++;
temp+=arr[j];
}
}
}
if(temp.length()>ans)
ans=temp.length();
}
return ans;
}
};