Skip to content

Commit 2095613

Browse files
authored
Merge pull request #1682 from Abhinavcode13/patch-40
Create MaxConcatenatedstr.java
2 parents b7d9330 + e4d0b0f commit 2095613

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

Strings/MaxConcatenatedstr.java

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
class Solution {
2+
public:
3+
// i: arr[i] we are currently looking at
4+
// mask: Bitmask that represents all the characters that have been added to the current string
5+
// If 0-th bit in mask is set, it means that we have added "a" in the current string
6+
int solve(vector<string> &arr, int i, int mask) {
7+
int n = arr.size();
8+
9+
if (i >= n)
10+
return 0;
11+
12+
// Skip concatenating arr[i]
13+
int curRes = solve(arr, i+1, mask)
14+
15+
// Mask to keep track of the characters that are present in arr[i]
16+
int curMask = 0;
17+
18+
// Check whether any character in arr[i] is present in current string, i.e.
19+
// Check whether (arr[i]-'a')-th bit is set in mask
20+
// If any existing character's bit is set, it means that we cannot concatenate arr[i]
21+
// to the given string and so return curRes only which contains the result of skipping arr[i]
22+
// Also, use curMask to maintain the characters in arr[i] that have been seen.
23+
// It is possible that arr[i] itself has duplicate characters in which case, we will not be able to concatenate arr[i]
24+
// So check whether (c-'a')-th bit is set in curMask and after that set the (c-'a')-th bit in curMask
25+
for (char &c: arr[i]) {
26+
if (mask & (1 << (c - 'a')))
27+
return curRes;
28+
29+
if (curMask & (1 << (c - 'a')))
30+
return curRes;
31+
32+
curMask |= (1 << (c - 'a'));
33+
}
34+
35+
// All the bits that were set in curMask will be now set in mask,
36+
// in order to add all characters of arr[i] to the current string
37+
mask |= curMask;
38+
39+
// We make a call to i+1 with the updated mask and arr[i]'s length being added
40+
curRes = max(curRes, (int) arr[i].length() + solve(arr, i+1, mask));
41+
return curRes;
42+
}
43+
44+
int maxLength(vector<string>& arr) {
45+
return solve(arr, 0, 0);
46+
}
47+
};

0 commit comments

Comments
 (0)