Converting one string to other using append and delete last operations in C++

C++Server Side ProgrammingProgramming

In this tutorial, we will be discussing a program to convert one string to other using append and delete last operations.

For this we will be provided with two strings. Our task is to calculate whether the first string can be converted into the second one by performing k operations of append and delete last element.

Example

#include <bits/stdc++.h>
using namespace std;
//checking if conversion between strings is possible
bool if_convert(string str1, string str2,
int k){
   if ((str1.length() + str2.length()) < k)
   return true;
   //finding common length of both string
   int commonLength = 0;
   for (int i = 0; i < min(str1.length(),
   str2.length()); i++) {
      if (str1[i] == str2[i])
      commonLength++;
      else
      break;
   }
   if ((k - str1.length() - str2.length() +
   2 * commonLength) % 2 == 0)
   return true;
   return false;
}
int main(){
   str1 = "tutorials", str2 = "point";
   k = 5;
   cout << endl;
   if (if_convert(str1, str2, k))
   cout << "Yes";
   else
   cout << "No";
   return 0;
}

Output

No
raja
Published on 29-Jan-2020 07:41:59
Advertisements