Append and Delete

You have two strings of lowercase English letters. You can perform two types of operations on the first string:

  1. Append a lowercase English letter to the end of the string.
  2. Delete the last character of the string. Performing this operation on an empty string results in an empty string.

Given an integer,k, and two strings,  and t, determine whether or not you can convert  to t by performing exactly  of the above operations on s. If it's possible, print Yes. Otherwise, print No.

Example:

Input: s = "hackerhappy", t = "hackerrank", k = 9
Output: Yes

Approach

C++

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

string appendAndDelete(string sstring tint k)
{

    int counti;
    for (i = 0s[i]t[i]i++)
    {
        if (s[i] != t[i])
            break;
    }
    int n1 = s.size(), n2 = t.size();
    count = n1 - i + n2 - i;

    if (k == count || k >= n1 + n2)
        return "Yes";
    else if (count % 2 == k % 2 && count <= k)
        return "Yes";
    else
        return "No";
}

int main()
{
    string s = "hackerhappy";
    string t = "hackerrank";

    int k = 9;

    cout << appendAndDelete(stk<< "\n";

    return 0;
}


No comments:

Post a Comment