检查一个字符串是否可以由另一个字符串中的字符组成
check if a string can be made from characters in another string
我想检查字符串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.
相关文章:
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 我如何通过引用将 c++ 字符串分配给另一个字符串
- 使用另一个字符串从字符串中删除空格
- 有没有办法使用 strcpy 将字符串数组复制到另一个字符串或其他数组中?
- 当分配一个字符串值并稍后通过分配另一个值进行更改时C++如何管理内存?
- 如何在不知道对应关系的情况下在字符串中搜索字符并将其分配给另一个字符?
- 如何在使用 getch 后在另一个字符串的末尾连接一个字符串
- 如何在另一个字符串的x位置插入一个字符串?
- 从 C 字符串构造 std::string 与从另一个 std::string 构造 std::string 不一致
- C++:递归地将字符串中一个字母的所有实例替换为另一个字母
- 在另一个字符串中插入文件扩展名之前的字符串
- 使用C++将一个字符串替换为另一个字符串
- 将字符从一个字符串简单分配到另一个字符串不起作用
- 将 int 转换为字符串,然后连接另一个变量以创建完整扩展名,然后将其转换为 const_char*
- 将字符串中的单个单词替换为另一个单词
- 将文本流中一个字符串的所有匹配项替换为另一个字符串
- 无法将字符串用作另一个类的参数
- 另一个字符串文字,UDL 迷宫
- 在给定字符串上使用 tolower() 和 isalpha() 并将其输出设置为另一个字符串
- 如何使用循环从另一个字符串创建一个没有空格的新字符串