Largest Merge of Two Strings in C++

C++Server Side ProgrammingProgramming

Let us suppose we have two strings 'a' and 'b' and a string 'merge'. The task is to fill the string 'merge' with the characters from 'a' and 'b' in such a way that,

  • If the string 'a' is non-empty, then remove the first character from the string 'a' and copy it into string 'merge'.
  • If the string 'b' is non-empty, then remove the first character from the string 'b' and copy it into string 'merge'.
  • If the strings 'a' and 'b' are non-empty, then remove the first characters from string 'a' and copy it into string 'merge' and then remove the first character (if any) from string 'b' and copy it into the string 'merge'.
  • Remove the characters from both the strings lexicographically, which means, if string 'a' is greater than string 'b', then remove the character from string 'a' and then string 'b'.
  • Return the string 'merge'.

For Example

Input-1:

a = “bacaa”

b = “abcaa”

Output:

babcacaaaa

Explanation:

Since the given string 'a' is lexicographically greater than the string 'b', we will extract the first character from string 'a', i.e., “b” and then from string 'b'. After extracting, the string will be “babcacaaaa”.

Approach to Solve this Problem

The recursive approach to solve this problem is that we will extract each character of string 'a' and string 'b' and will check if the characters of string 'a' are lexicographically greater than the other string and finally concatenate to string 'merge'.

We will find the substring of each character after a number of positions and concatenate into 'merge' if it is lexicographically greater than the other string.

  • Take two input strings 'a' and 'b'.
  • A recursive string function concatenateLargest(string a, string b) takes two strings as the input and returns the largest string after concatenation, i.e., (string 'a' + string 'b').
  • If both the strings are empty, then return string 'a' + string 'b'.
  • If string 'a' is less than or equal to string 'b', then extract the first character and call the function recursively for other characters.
  • If string 'b' is less than or equal to string 'b', then extract the first character and call the function recursively for other characters.
  • Return the concatenated string.

Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
string concatenateLargest(string a, string b) {
   if (a.size() == 0 or b.size() == 0) {
      return (a + b);
   }
   if (a <= b)
      return b[0] + concatenateLargest(a, b.substr(1));
   else
      return a[0] + concatenateLargest(a.substr(1), b);
}
int main() {
   string a = "bacaa";
   string b = "abcaa";
   cout << concatenateLargest(a, b) << endl;
   return 0;
}

Running the above code will generate the output as,

Output

bacabcaaaa

The two strings “bacaa” and “abcaa” will become “bacabcaaaa” after merging according to the given problem.

raja
Published on 23-Feb-2021 09:41:04
Advertisements