Maximum Length of a Concatenated String with Unique Characters in C++


Suppose we have an array of strings arr. The string s is a concatenation of a sub-sequence of arr which have unique characters. Find the maximum possible length of s. If the input is like [“cha”, “r”, “act”, “ers”], then the output will be 6, possible solutions are “chaers” and “acters”.

To solve this, we will follow these steps −

  • make one method called ok() and this will take strings s and t. This will act like below
  • make one map x
  • for i in range 0 to size of s
    • increase x[s[i]] by 1
    • if x[s[i]] > 1, then return false
  • for i in range 0 to size of t
    • increase x[t[i]] by 1
    • if x[t[i]] > 1, then return false
  • return true
  • the actual method will be look like below −
  • make an array of strings called v, and ans := 0, insert one empty string into v
  • for i in range 0 to size of arr
    • n := size of v
    • for j in range 0 to n – 1
      • if ok(v[j], arr[i]) is true, then
        • t := v[j] + arr[i]
        • insert t into v
        • ans := max of ans and size of t
  • return ans

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   bool ok(string s, string t){
      map <char, int > x;
      for(int i = 0; i < s.size(); i++){
         x[s[i]]++;
         if(x[s[i]] >1)return false;
      }
      for(int i = 0; i < t.size(); i++){
         x[t[i]]++;
         if(x[t[i]]>1)return false;
      }
      return true;
   }
   int maxLength(vector<string>& arr) {
      vector <string> v;
      int ans = 0;
      v.push_back("");
      for(int i = 0; i < arr.size(); i++){
         int n = v.size();
         for(int j = 0; j < n; j++){
            if(ok(v[j],arr[i])){
               string t = v[j]+arr[i];
               v.push_back(t);
               ans = max(ans,(int)t.size());
            }
         }
      }
      return ans;
   }
};
main(){
   vector<string> v = {"cha","r","act","ers"};
   Solution ob;
   cout << (ob.maxLength(v));
}

Input

["cha","r","act","ers"]

Output

6

Updated on: 02-May-2020

330 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements