【问题标题】:C++ substring matching implementationC++子串匹配实现
【发布时间】:2012-09-27 07:57:26
【问题描述】:

我有两个字符串,例如“hello”和“eo”,我希望在两个字符串之间找到重复的字符,即:在本例中为“e”和“o”。

我的算法会这样

 void find_duplicate(char* str_1, char* str_2, int len1, int len2)
 {
     char c ;

     if(len1 < len2)
     {
        int* idx_1 = new int[len1]; // record elements in little string
        // that are matched in big string
        for(int k = 0 ; k < len1 ; k++)
              idx_1[k] = 0;

        int* idx_2 = new int[len2]; // record if element in str_2 has been 
        // matched already or not
        for(int k = 0 ; k < len2 ; k++)
              idx_2[k] = 0;

        for(int i = 0 ; i < len2 ; i++)
        {     
            c = str_1[i];

            for(int j = 0 ; j < len1 ; j++)
            {
                 if(str_2[j] == c)
                 {
                    if(idx_2[j] == 0) // this element in str_2 has not been matched yet
                    {
                         idx_1[i] = j + 1; // mark ith element in idx as matched in string 2 at pos j
                         idx_2[j] = 1;
                    }
                 }
             }
         }

         // now idx_1 and idx_2 contain matches info, let's remove matches.
         char* str_1_new = new char[len1];
         char* str_2_new = new char[len2];
         int kn = 0;
         for(int k = 0 ; k < len1 ; k++)
         {
            if(idx_1[k] > 0)
            {
                 str_1_new[kn] = str_1[k];
                 kn++;
            }
         }

         kn = 0;
         for(int k = 0 ; k < len2 ; k++)
         {
             if(idx_2[k] > 0)
             {
                 str_2_new[kn] = str_2[k];
                 kn++;
             }
         }
      }
      else
      {
            // same here, switching roles (do it yourself)
       }
  }

我觉得我的解决方案很尴尬: - 在第一个 if/else 和代码重复中两种情况的对称性 - 时间复杂度:2*len1*len2 操作用于查找重复项,然后 len1 + len2 操作用于删除 - 空间复杂度:两个 len1 和两个 len2 char*。

如果没有给出len1len2 怎么办(使用和不使用STL 向量)?

你能提供这个算法的实现吗?

谢谢

【问题讨论】:

  • 我会对字符串中的字符进行排序并一次性比较它们。

标签: c++ string algorithm substring string-matching


【解决方案1】:

首先,这不是子字符串匹配的问题——它是在两个字符串之间寻找共同字符的问题。

您的解决方案适用于 O(n*m),其中 n=len1m=len2 在您的代码中。您可以通过计算每个字符串中的字符数(其中 c 等于字符集的大小)在 O(n+m+c) 时间内轻松解决相同的问题。这个算法叫做counting sort

在您的情况下实现此示例代码:

#include <iostream>
#include <cstring> // for strlen and memset

const int CHARLEN = 256; //number of possible chars

using namespace std;

// returns table of char duplicates
char* find_duplicates(const char* str_1, const char* str_2, const int len1, const int len2)
{
  int *count_1 = new int[CHARLEN];
  int *count_2 = new int[CHARLEN];
  char *duplicates = new char[CHARLEN+1]; // we hold duplicate chars here
  int dupl_len = 0; // length of duplicates table, we insert '\0' at the end
  memset(count_1,0,sizeof(int)*CHARLEN);
  memset(count_2,0,sizeof(int)*CHARLEN);
  for (int i=0; i<len1; ++i)
  {
    ++count_1[str_1[i]];
  }
  for (int i=0; i<len2; ++i)
  {
    ++count_2[str_2[i]];
  }

  for (int i=0; i<CHARLEN; ++i)
  {
    if (count_1[i] > 0 && count_2[i] > 0)
    {
      duplicates[dupl_len] = i;
      ++dupl_len;
    }
  }
  duplicates[dupl_len]='\0';
  delete count_1;
  delete count_2;
  return duplicates;
}

int main()
{
  const char* str_1 = "foobar";
  const char* str_2 = "xro";
  char* dup =   find_duplicates(str_1, str_2, strlen(str_1), strlen(str_2));
  cout << "str_1: \"" << str_1 << "\" str_2: \"" << str_2 << "\"\n";
  cout << "duplicates: \"" << dup << "\"\n";
  delete dup;
  return 0;
}

请注意,我也在此处对输出进行排序。如果你不想这样做,你可以跳过第二个字符串中的字符计数,然后开始比较重复。

但是,如果您希望能够检测到同一个字母的多个重复项(例如,如果“banana”和“arena”应该输出“aan”而不是“an”),那么您只需减去计入当前解决方案并相应地调整输出。

【讨论】:

  • O(n+m+c),其中 c 是字符集的大小
  • @Zaroth 请注意,new int[CHARLEN](); 将使用 0 个元素初始化您的数组。您还可以使用std::vector 简化很多代码(初始化为0,不需要显式删除)
  • @log0 () 技巧有点巫毒;因为这是一个教育性的答案,所以我试图让我的代码尽可能地可读。另外,请注意,OP 请求了一个不使用std::vector 的解决方案。
  • @KarolyHorvath/Zaroth 我认为您可以只使用一个计数向量,并在您发现计数不同于 0 时简单地添加字符。在这种情况下,复杂度确实是 O(len1+len2)内存占用 ~256
  • @Zaroth 我不认为 OP 反对使用 st::vector 他想知道它是否正在改变复杂性。
【解决方案2】:
std::vector<char> duplicates;
for (auto c1: std::string(str_1))
  for (auto c2: std::string(str_2))
    if (c1 == c2)
      duplicates.push_back(c1);

或者如果您没有兼容 c++11 的编译器。

std::vector<char> duplicates;
std::string s1(str_1);
std::string s2(str_2);
for (std::size_t i = 0; i < s1.size(); i++)
  for (std::size_t j = 0; j < s2.size(); j++)
    if (s1[i] == s2[j])
      duplicates.push_back(s1[i]);

--基于Zaroth的回答

std::vector<int> count(256,0);
for (auto c : std::string(str_1))
 count[c] += 1;
for (auto c : std::string(str_2))
 if (count[c] > 0)
   duplicates.push_back(c);

【讨论】:

  • for (auto c1: std::string(str_1)),这是 C++11,对吧?如果我在 vs2010 中使用 C++ 会怎样
  • 这是否意味着在运行时 std::size_t 是字符串中字符的“已知”大小?
  • @fonjibe vs2010 支持自动关键字blogs.msdn.com/b/vcblog/archive/2010/04/06/…
  • 内循环中有 i++ 而不是 j++。
  • @fonjibe for (auto c1: std::string(str_1)) 表示:对于使用str_1 构造的临时std::string 中的每个元素c1
猜你喜欢
  • 1970-01-01
  • 2012-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多