【问题标题】:check if a string can be made from characters in another string检查一个字符串是否可以由另一个字符串中的字符组成
【发布时间】:2012-03-13 19:09:11
【问题描述】:

我想检查是否可以通过从 string2 中获取字符并将它们按正确的顺序排列来生成 string1。最有效的方法是什么?

比如我有2个字符串如下图:

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

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

哦,编程语言是 C++。

【问题讨论】:

    标签: c++ string


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      #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.
      

      【讨论】:

        猜你喜欢
        • 2012-07-12
        • 2021-10-04
        • 1970-01-01
        • 2019-05-11
        • 1970-01-01
        • 2013-05-12
        • 2013-03-13
        • 2011-02-07
        相关资源
        最近更新 更多