Program to check whether a string is a valid shuffle of two strings or not in C++

Check if string is shuffled substring of another string

Today we will be learning about how to Check if string is shuffled substring of another string.

Input string :- 

  string 1 :- ABC

  string 2 :- DEF

  string 3 :- ABCDEF

Output:- here every character in string 3 is present in the shuffled form of string one and string 2. that’s why string 3 is shuffled substring if another string.

Find Duplicates Characters

Algorithm

  • First we will take the two string and the third string that need to be checked as input
  • Then will make a function is valid and pass the string 1 string 2 and string 3 as parameter 
  • In the function will sort all the three string 
  • Run a loop throughout the length of 3rd string and in that loop check if the the  first[i] == result[k] 
  • Then increment value of i else if  second[j] == result[k] then j++ otherwise return false
  • Out of the loop return true.
Check If String Is Shuffled Substring of Another String

C++ Code :-

  #include<bits/stdc++.h>
  using namespace std;

  bool isvalid(string first, string second, string result){
  if(first.size() + second.size() != result.size()) {
    return false;
  }

//Sort all the three string sort(first.begin(),first.end()); sort(second.begin(),second.end()); sort(result.begin(),result.end());

//iterate through the entire length of result string int i=0,j=0,k=0; while( k < result.size()){

//check if character of string first is equal to first character of result
if( i<first.length() && first[i] == result[k] ) i++;

//Check if character of string Second is equal to first character of result else if( j<second.length() && second[j] == result[k] ) j++;

//If any of the above condition is not true then return false else return false; k++; } return true; } int main() { string str,str1,str2;

//Take two string as input from the user cout<<"Enter the value of string 1 : "; cin>>str1; cout<<"Enter the value of string 2 : "; cin>>str2; cout<<"Enter the string that need to be checked : "; cin>>str; if(isvalid(str1,str2,str)){ cout<<"Yes its a valid shuffle "; } else{ cout<<"No its not a valid shuffle "; } return 0; }

Output:-

Enter the value of string 1 : ADF
Enter the value of string 2 : PRE
Enter the string that need to be checked : PREPEP
No its not a valid shuffle
Enter the value of string 1 : xXD
Enter the value of string 2 : CD
Enter the string that need to be checked : xXCDD
Yes its a valid shuffle