编写一个反转输入字符串的递归函数 [英] Write a recursive function that reverses the input string

查看:227
本文介绍了编写一个反转输入字符串的递归函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在读C ++ For Everyone一书,其中一个练习说写一个函数 string reverse(string str)其中返回值是 str



有人可以写一些基本代码并向我解释吗?我昨天一直盯着这个问题,不能弄清楚。我已经得到的最远的函数返回 str 的第一个字母(我仍然不知道它是怎么发生的)



这是我的(在发布此问题后一小时):

  str)
{
string word =;

if(str.length()< = 1)
{
return str;
}
else
{
string str_copy = str;
int n = str_copy.length() - 1;
string last_letter = str_copy.substr(n,1);

str_copy = str_copy.substr(0,n);
word + = reverse(str_copy);
return str_copy;
}
return word;
}



如果我输入Wolf,它会返回Wol。有人帮我在这里
如果我返回字而不是返回str_copy 然后我得到一个 w
如果我返回last_letter ,那么我得到一个 l

解决方案

我有两分钟,所以我将解释递归算法本身。以输入为例,它应该产生tupni。




  • 如果字符串为空或单个字符,则返回不变。

  • 否则


    1. 删除第一个字符。

    2. 颠倒剩余的字符串。

    3. 将以上第一个字符添加到反转的字符串中。

    4. 返回新的字符串。

    ul>

    I've been reading the book C++ For Everyone and one of the exercises said to write a function string reverse(string str) where the return value is the reverse of str.

    Can somebody write some basic code and explain it to me? I've been staring at this question since yesterday and can't figure it out. The furthest I've gotten is having the function return the first letter of str (Which I still don't know how it happened)

    This is as far as I got (An hour after posting this question):

    string reverse(string str)
    {
        string word = "";
    
        if (str.length() <= 1)
        {
            return str;
        }
        else
        {
            string str_copy = str;
            int n = str_copy.length() - 1;
            string last_letter = str_copy.substr(n, 1);
    
            str_copy = str_copy.substr(0, n);
            word += reverse(str_copy);
            return str_copy;
        }
        return word;
    }
    

    If I enter "Wolf", it returns Wol. Somebody help me out here If I return word instead of return str_copy then I get a w If I return last_letter then I get an l

    解决方案

    I've got two minutes so I'll instead explain the recursive algorithm itself. Take the example "input" which should produce "tupni". You can reverse the string recursively by

    • If the string is empty or a single character, return it unchanged.
    • Otherwise,

      1. Remove the first character.
      2. Reverse the remaining string.
      3. Add the first character above to the reversed string.
      4. Return the new string.

    这篇关于编写一个反转输入字符串的递归函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆