[英]check if a string can be made from characters in another string
我想检查是否可以通过从string2提取字符并按正确顺序将它们制成。 最有效的方法是什么?
例如,我有2个字符串,如下所示:
string s1 = "ABCDASFSADFAF", s2 ="ABCDFGSAGSRASFSFASFASDADFAFDSAGFAS";
如您所见,我们可以从字符串s2中的字符组成字符串s1,因此string1存在于string2中。 因此,基本上,我需要检查您是否可以从字符串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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.