【问题标题】:Recursive function to generate string does not contain two adjacent identical substring c++生成字符串的递归函数不包含两个相邻的相同子字符串c ++
【发布时间】:2015-06-09 23:05:50
【问题描述】:

我有一项难以处理的任务。任务是:创建一个递归函数,可以生成一个长度为 N (N AABACA - 因为'A'是'A'; ABCBCA - 因为 'BC' 对应于 'BC' 而 ABCABC 也是错误的,因为 'ABC' 对应于 'ABC'。

我做了一个版本的程序,但是是一种迭代的方式,这里是代码:

#include <iostream>
#include <ctime>

using namespace std;

const char letters[] = "ABC";

char generate_rand()
{

     return letters[rand() % 3];

}

int check(char *s, int pos) 
{

    for (int i = 1; i <= (pos + 1)/2; i++) 
    {

        int flag = 1;

        for (int j = 0; j < i; j++)

        if (s[pos-j] != s[pos-i-j]) 
        {

            flag = 0; 
                break;

        }

        if (flag)
            return 1;

    }
    return 0;
}

int main() 
{

    char s[100];
    int n;

    cout << "enter n: ";
    cin >> n;

    srand(time(NULL));

    for (int i = 0; i < n; i++) 
    {

        do
        {

            s[i] = generate_rand();

        } while (check(s, i));

        cout << s[i] << " ";

    }

    cout << " ok" << endl;

    system("pause");
    return 0;
}

我觉得递归函数的入口可能需要是字符串中的字符数,它会寻求与相邻字符串重复,每次加1,但不超过原字符串长度的一半,但不知道怎么做。

【问题讨论】:

  • 您的代码似乎不包含任何递归函数。

标签: c++ string function recursion substring


【解决方案1】:

让我们从一个简单的递归函数开始,它打印 10 个字母但不检查任何内容:

void addLetter(char* buf, int max_length)
{
   int len = strlen(buf);
   buf[len] = generate_rand();
   if (strlen(buf) < max_length) 
      addLetter(buf);
}

int main()
{
   srand(time(NULL)); //I forgot srand!
   int max_length = 10; //ask user to input max_length, like you had earlier
   char buf[100];
   memset(buf,0,sizeof(buf));
   addLetter(buf, max_length);
   printf("\n%s\n", buf);
   return 0;
}

现在让我们更改递归函数,让它只检查 1 个字母:

void addLetter(char* buf, int max_length)
{
   int len = strlen(buf);
   buf[len] = generate_rand();

   if (len > 0)
   {
      if (buf[len] == buf[len-1])
         buf[len] = 0;
   }

   if (strlen(buf) < max_length) 
      addLetter(buf);
}

下一步,检查2个字母和以前的字母等。你应该可以从这里拿走。

【讨论】:

  • 可以生成字符串,但是每次都成对生成相同的字符。例如 CBCBAB 也许这是由于函数 srand ()。
  • 是的,我忘了 srand。像以前一样将srand 放回main
  • 现在可以工作,但有时会生成相同的子字符串。
  • 是的,它不检查那部分。你必须自己完成它。我也忘了,n 应该是addLetter(char* buf, int n); 中的一个参数,或者叫它max_length
猜你喜欢
  • 2016-11-26
  • 1970-01-01
  • 2016-05-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多