检查一个字符串是否可以由另一个字符串中的字符组成

check if a string can be made from characters in another string

本文关键字:字符串 另一个 字符 是否 一个 检查      更新时间:2023-10-16

我想检查字符串1是否可以通过从字符串2中提取字符并按正确的顺序排列来生成。最有效的方法是什么?

例如,我有两个字符串,如下所示:

string s1 = "ABCDASFSADFAF", s2 ="ABCDFGSAGSRASFSFASFASDADFAFDSAGFAS";

正如您所看到的,我们可以从字符串s2中的字符生成字符串s1,因此字符串g1存在于字符串2中。所以基本上,我需要检查你是否可以从字符串s2中生成字符串s1。做这样的事情最有效的方法是什么?我有一个想法,通过循环,检查每个字母在字符串中的次数,然后对第二个字符串执行同样的操作,然后将数组的值与存储的信息进行比较,如果字符串s2字母数组的字母数大于或等于字符串s1数组的字母,那么我们将能够从s2中生成s1。

哦,编程语言是C++。

对每个字符串(std::sort)进行排序,然后使用std::includes

您可以通过循环s1并从s2的副本中删除每个字符的第一个查找结果来检查这一点:

#include <string.h>
using namespace std;
string s1 = "ABCC", s2 = "DCBA";
string copy = s2;
size_t found;
bool contains = true;
for(int i = 0; i < s1.length(); i++)
{
    found = copy.find(s1[i]);
    if(found == string::npos)
    {
        contains = false;
        break;
    }
    copy = copy.replace(found, 1, "");
}
// Now 'contains' is true if s1 can be made from s2, false if it can't.
// If also 'copy' is empty, s1 is an anagram of s2.
相关文章: