【问题标题】:count and say using recursion in C++在 C++ 中使用递归计算和说
【发布时间】:2018-06-15 14:05:53
【问题描述】:

给定“n”,问题是生成第 n 个 Count 和 Say 序列。 Here是问题描述。

我试图通过递归来解决这个问题:

编辑: 基本上遍历字符串并计算连续的1s、2s(或其他)并将(计数+我们计算的那个数字)(顺便说一下,它是一个字符串)附加到最终要返回的主字符串。 该链接现在有效。

string gofind(int N){
    if(N==1) return "1";
    else{
        string temp = gofind(N-1);
        ostringstream str1;
        string* t  = &(temp);
        int count;
        string n;
        while(*t!="\0"){
            count=1;
            while(*t==*(t+1)) {
                count++;
                t++;
            }
            str1<<count;//basically to convert int to str
            string geek = str1.str();
            n.append(geek+*t);
            t++;
        }
        return n;
    }
}

这会在运行时“bad_alloc”引发异常。这段代码中可能有很多错误。 有人能指出什么吗?什么是正确的递归解决方案。

【问题讨论】:

  • 我强烈建议您学习如何使用调试器以及如何调试您的程序。一个好的调试器可以让你逐行检查代码并检查变量的值,这对于推断问题所在非常有帮助
  • 看来您将t 视为char *,而不是string *。
  • 这不是递归的好用法。您可以迭代,并记住上一行。
  • 你给的链接失效了。
  • @Jeffrey 你能详细说明原因吗?我认为这有点类似于阶乘问题,所以我采用了这种方法。

标签: c++ string algorithm


【解决方案1】:

这不是遍历字符串的正确方法:

string* t  = &(temp); // Please no!
while(*t!="\0"){

这为您提供了指向 string 存储其控制块的位置的指针,即其大小等信息 - 这 不是 字符数据所在的位置。此外,您将此指针视为那里有一个 stringss 数组,而不是字符数组(两者都不是)。

你可以通过简单的索引来遍历字符串:

for (int i = 0; i < temp.size() - 1; ++i)
{
  count = 1;
  while ((i+1 < temp.size()) && (temp[i] == temp[i+1]))
  {
    count++;
    i++;
  }
}

我认为您可以从这里找到完整的解决方案。

【讨论】:

  • 鉴于用户已经承认他们的代码可能包含几个重大错误,我认为强调该特定问题的严重性是具有指导意义的。但是我听从了你的建议,根据你的比较去掉了重点。随意提出其他措辞。
  • 我现在更喜欢它了。我尊重我以这种实事求是的方式接受我的批评。
  • @MaxLanghof 非常感谢。这真的很愚蠢,是的,被误导了。
  • 解决了这个问题。现在解决方案工作得很好:D
【解决方案2】:
string gofind(int N){
    if(N==1) return "1";
    if(N==2) return "11";
    else{
        string temp = gofind(N-1);
        int count;
        string n;
        for (int i=0;i<temp.size();i++){
            count=1;
            while((temp[i]==temp[i+1])&&(i<temp.size()-1)){
                i++;
                count++;
            }
            ostringstream str1;//all of  this to
            str1<<count;//basically to convert 
            string geek = str1.str();//int to str
            n.append(geek+temp[i]);
        }
        return n;
    }
}

顺便说一下,这是更正后的代码。

【讨论】:

    【解决方案3】:

    #include
    使用命名空间标准;

    void func(string s,int p){

    if((s.substr(1)).length()==0){
        return;
    }
    if(s[0]==s[1]){
        p=p+1;
        func(s.substr(1),p);
    }
    if(s[0]!=s[1]){
        cout<<p<<s[0];
        func(s.substr(1),p=1);
    }
    if((s.substr(1)).length()==1){
        cout<<p<<s[1];
    }
    

    }

    int main(){

    string s;
    cin>>s;
    func(s,1);
    return 0;
    

    }

    【讨论】:

    • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center。
    猜你喜欢
    • 1970-01-01
    • 2022-07-06
    • 1970-01-01
    • 2017-08-22
    • 1970-01-01
    • 1970-01-01
    • 2014-04-12
    • 1970-01-01
    • 2012-07-19
    相关资源
    最近更新 更多