Check if a string can become empty by recursively deleting a given sub-string in C++

C++Server Side ProgrammingProgramming

Suppose, we are given two strings, str1 and str2. str2 is a substring of str1, and we can delete str2 from str1. It is possible, that the string str2 appears multiple times in str1. Our goal here is to find out if str1 becomes a null string if we keep removing str2 from str1 multiple times. If it is possible we return 1, otherwise 0.

So, if the input is like str1 = "CCCPPPPPP", str2 = "CPP"; then the output will be true.

To solve this, we will follow these steps −

  • while size of str1 > 0, do −
    • index := return the string start position of str2 in str1
    • if index is same as -1, then −
      • Come out from the loop
    • delete str2 from str1
  • return 1 if size of str1 is similar to 0, otherwise 0.

Example (C++)

Let us see the following implementation to get better understanding −

 Live Demo

#include<bits/stdc++.h>
using namespace std;
bool solve(string str1, string str2) {
   while (str1.size() > 0) {
      int index = str1.find(str2);
      if (index == -1)
      break;
      str1.erase(index, str2.size());
   }
   return (str1.size() == 0);
}
int main() {
   string str1 = "CCCPPPPPP", str2 = "CPP";
   cout<<solve(str1, str2)<<endl;
   return 0;
}

Input

"CCCPPPPPP", "CPP"

Output

1
raja
Published on 18-Jan-2021 11:45:26
Advertisements