Count of strings that can be formed from another string using each character at-most once in C++


We are given two strings i.e. str1 and str2 and the task is to calculate the count of strings that can completely be generated from another string, but we can use one character once for forming the string. Like, we will take two strings str1 and str2 and check for the occurrence of str2 in str1 by using the character of str1 exactly once.

Input − str_1 = "technical learning", str_2 = "learning"

Output − Count of strings that can be formed from another string using each character at-most once are − 1

Explanation − As we can see str_2 occurs in str_1 exactly once. So, the count of str_1 in str_2 is 1.

Input − str_1 = “ellohsehelloabcoelhl, str_2 = “helllo”

Output − Count of strings that can be formed from another string using each character at-most once are − 3

Explanation − As we can see str_2 is hello therefore we will check for the formation of word hello using characters of str_1 exactly once. As we can see, there are 3 formations of the word hello in str_1 therefore the count is 3.

Approach used in the below program is as follows

  • Input the string str_1 and str_2 and calculate their corresponding length and pass the data to the function for further processing.

  • Declare a temporary variable count to store the count of str_2 in str_1 and initialise it with INT_MAX. INT_MAX is used in C++ to specify the maximum value a variable can hold and the value of INT_MAX is +2147483647.

  • Create an array of size 26 as we have 26 alphabets in English and initializes it with 0.

  • Start loop FOR from 0 till the length of a string str_1 and set arr[str_1[i] - ‘a’] by 1

  • Start another loop FOR from 0 till the length of a string str_2 and set count as minimum of count or arr[str_2[i] - ‘a’].

  • Return count

  • Print the result.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int atmost_once(string str_1, int len_str1, string str_2, int len_str2){
   int count = INT_MAX;
   int arr[26] = { 0 };
   for (int i = 0; i < len_str1 ; i++){
      arr[str_1[i] - 'a'] += 1;
   }
   for (int i = 0; i < len_str2; i++){
      count = min(count, arr[str_2[i] - 'a']);
   }
   return count;
}
int main(){
   string str_1 = "technical learning";
   int length_str1 = str_1.length();
   string str_2 = "learning";
   int length_str2 = str_2.length();
   cout<<"Count of strings that can be formed from another string using each character at-most
once are: "<<atmost_once(str_1,length_str1, str_2, length_str2);
   return 0;
}

Output

If we run the above code it will generate the following output −

Count of strings that can be formed from another string using each character at-most once are: 1

Updated on: 02-Dec-2020

252 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements