这个递归代码有什么问题?

时间:2012-12-07 21:53:26

标签: c++ recursion stack-overflow

我正在使用CodeLab for C ++进行在线工作,我不确定我的代码有什么问题。这是一个问题:

编写一个递归的int值函数len,它接受一个字符串并返回字符串中的字符数。  字符串的长度是: 如果字符串是空字符串(“”),则为0。 比第一个字符之外的其余字符串的长度多1个。

这是我的代码:

int len(string s)
{
  if (s.length()==0)
    return 0;
 else
 {
    return 1+(len(s)-1);
 }
}

它说我有运行时错误。 有什么帮助吗?

感谢。

4 个答案:

答案 0 :(得分:11)

好吧:

     return 1+(len(s)-1);

字符串的长度永远不会减少。所以你最终会有一个stackoverflow,因为你从来没有打过你的基本情况(s.length() == 0).你需要得到一个子串,其中s的长度减少1:

     return 1+(len(s.erase(0,1))); // erases 1 char from beginning then recurses

希望这纯粹是学术性的,因为std::string有一个length方法可以在不变的时间内运行。 (更不用说从字符串前面删除可能非常低效 - 请参阅与char *一起使用的其他答案)

答案 1 :(得分:3)

len(s)永远不会减少并导致堆栈溢出。我会做类似的事情:

int len(const char * s) {
    if(*s == '\0')
        return 0;
    else
        return 1 + len(s+1); 
}

答案 2 :(得分:3)

您永远不会在代码中修改s,因此如果s不为空,则继续使用相同的参数再次调用相同的函数;你从不停止。您的计算机没有堆栈空间,程序崩溃。

其他人给了你一些想法/选择。这是我的建议:

int len(const std::string &s, int start)
{
    /* If we are starting at the end, there's no more length */
    if(start == s.length())
        return 0;

    /* one plus whatever else... */
    return 1 + len(s, start + 1);
}

假设str是您希望获得长度的字符串,可以将其称为:len(str, 0)

如果您需要使用const char *版本,请尝试以下操作:

int len(const char *s)
{
    if((s == NULL) || (*s == 0))
        return 0; /* we ran out of string! */

    return 1 + len(s + 1);
}

答案 3 :(得分:0)

另一种解决方案:

int len(string s)
  {
  if (s.length()==0)
      return 0;
  else
     {
     s = s.substr(0, s.size()-1);
     return 1+(len(s));
     }
  }
相关问题