如何通过删除最少数量的字符来获取子字符串?

How to get a substring by deleting minimum number of characters?

在这个问题中,我们将 2 个字符串作为输入,比如 s1 和 s2。

现在,首先我们需要检查 s2 是否是 s1 的子序列。如果没有,打印编号

但如果是,我们需要打印从s1中删除的最少字符数才能得到s2。

例如- thistext 文本

这里是直接查找文本,不删除任何字符,所以答案是0。

eg-可爱的友情脆

在这种情况下,答案是 9。

我到目前为止所做的,

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

int checkIfSub(string s1, string s2, int m, int n)
{
    int j = 0;
    for(int i = 0; i < m && j < n; i++)
        if(s1[i] == s2[j])
            j++;
    if(j == n)
        return 0;
    else 
        return 1;
}
int check(string s1, string s2)
{
    int count = 0; string s3;
    if(checkIfSub(s1, s2, s1.length(), s2.length()) == 1 || s2.length() > s1.length())
    {
        cout << "NO\n"; return 0;
    }
    int j = 0;
    for(int i = 0; i < s1.length(); i++)
    {
        if(s1[i] == s2[j])
        {
            s3[j] = s1[j];
            j++; continue;
        }
        count++;
    }
    cout << "YES " << count << "\n";
    return 0;
}

int main() {

    string s1, s2;
    cin >> s1 >> s2;
    check(s1, s2);

    return 0;
}

我的代码在第二个示例中运行良好,但在第一个示例中失败了。

(这是我在网上看到的一些采访中问到的问题。)

尝试这样的事情:

#include <iostream>
#include <string>
using namespace std;

bool check(const string &s1, const string &s2, int &minToDelete)
{
    minToDelete = 0;
    bool anySubSeqFound = false;

    if (s2.empty())
        return false;

    string::size_type first = 0;
    while ((first = s1.find(s2[0], first)) != string::npos)
    {
        int numDeleted = 0;
        bool isSubSeq = true;

        string::size_type next = first + 1;
        for(string::size_type j = 1; j < s2.size(); ++j)
        {
            string::size_type found = s1.find(s2[j], next);
            if (found == string::npos)
            {
                isSubSeq = false;
                break;
            }
            numDeleted += (found - next);
            next = found + 1;
        }

        if (isSubSeq)
        {
            if (anySubSeqFound)
            {
                if (numDeleted < minToDelete)
                    minToDelete = numDeleted;
            }
            else
            {           
                anySubSeqFound = true;
                minToDelete = numDeleted;
            }
        }

        ++first;
    }

    return anySubSeqFound;
}

int main()
{
    int minToDelete;

    if (check("thistext", "text", minToDelete))
        cout << "yes, delete " << minToDelete << endl;
    else
        cout << "no" << endl;

    if (check("cutefriendship", "crisp", minToDelete))
        cout << "yes, delete " << minToDelete << endl;
    else
        cout << "no" << endl;
}

Live Demo