【问题标题】:Converting a recursive code to reverse a string into an iterative one in c++在c ++中将递归代码转换为将字符串反转为迭代代码
【发布时间】:2019-05-18 03:24:36
【问题描述】:

这是我的代码包含一个递归代码,我想将它转换为一个迭代的,但我希望它通过递归的方式来反转字符串exactky .. 有可能吗 我的意思是划分它

   #include <iostream>
#include <string.h>
using namespace std;

string reverse (string temp, int length)
{
    if (length == 1)
    {
        return temp;
    }
    else
    {
        int t = (temp.length() + 1) / 2;
        return
            reverse(
                temp.substr(t, temp.length() - 1),
                t
            ) +
            reverse(
                temp.substr(0, t),
                t
            );
    }
}

int main() {
    string s;
    cin>>s;
    string rev = reverse(s, s.length());
    cout <<"\n"<<rev;
    cin>>s;

    return 0;
}

【问题讨论】:

  • “没有”是什么意思?你遇到什么问题?发布的代码编译并似乎反转了输入的字符串。
  • 如果我在函数 reverse 的返回之前插入一个“cout
  • 程序以hellokitty 作为输入正常工作(结果:yttikolleh)。您应该精确地输出您期望的输出。你想看看步骤吗?如果是,请edit您的问题并向我们展示您期望的确切输出。

标签: arrays string recursion dynamic iteration


【解决方案1】:

用于反转stringnon-recursive 版本的代码可以通过将每个i 位置与len - i - 1 交换最多一半来完成,如下所示:

#include <iostream>
#include <string.h>
using namespace std;
int main() {
    string s;
    cin>>s;
    // Itearative code for reversing string s
    int len = s.size();
    int leftIdx = 0, rightIdx = len - 1;
    while (leftIdx < rightIdx) {
        swap(s[leftIdx], s[rightIdx]); // swapping index (i) with (len - i - 1)
        leftIdx++, rightIdx--;
    }
    cout<<s<<endl;
    return 0;
}

【讨论】:

  • 能否请您看一下我刚刚添加的示例
猜你喜欢
  • 2021-02-11
  • 1970-01-01
  • 2015-08-22
  • 1970-01-01
  • 1970-01-01
  • 2016-01-26
  • 2017-03-05
相关资源
最近更新 更多