C++:使用递归反转字符串

C++: Reverse a string using recursion

本文关键字:字符串 递归 C++      更新时间:2023-10-16

我正在尝试通过反转来修改通过引用传递它的字符串例如:单词海豚,它只使用递归。我无法在修改其标头的函数中添加更多参数。 我现在的输出是od而不是海豚,我认为它只做最后两个字母,老实说我不知道为什么。有什么我应该改变的吗?这是我的代码。

void reverse(string &word) {
if (word.length() == 1 || word.length() == 0) {
if (word.length() == 1) {
word = word;
}
else if (word.length() == 0) {
word = "nothing to reverse";
}
}
else {
string temp;
if (temp.length() == 0) {
temp = "";
temp = temp+word.substr(word.length() - 1, 1);
word.pop_back();
if (word.length() == 0) {
word = temp;
}
else if (word.length() == 1) {
//temp = temp + word.substr(word.length() - 1, 1);
temp = temp + word;
word.pop_back();
word = temp;
}
else {
reverse(word);
}
}
else {
temp = temp + word.substr(word.length() - 1, 1);
word.pop_back();
if (word.length() == 0) {
word = temp;
}
else if (word.length() == 1) {
//temp = temp + word.substr(word.length() - 1, 1);
temp = temp + word;
word.pop_back();
word = temp;
}
else {
reverse(temp);
}
}
}

}

算法是这样的:

  • 如果字符串长度小于 2,则返回
  • 去除单词的第一个和最后一个字符以创建子字符串
  • 归调用子字符串上的reverse
  • 从递归返回后,为原始"最后一个字符"添加前缀,并在原始"第一个字符"后缀以完成字符串

给你:

void reverse(string& word)
{
size_t len = word.size();
if (len < 2)
{
return;
}
char first = word[0];
char last = word[len - 1];
string inner;
if (len > 2)
{
inner = word.substr(1, len - 2);
reverse(inner);
}
word = last + inner + first;
}

实现相同目标的非递归方式可以是:

void reverseString(std::string& input)
{
const size_t inputStringLength = input.size();
for (size_t index = 0; index < inputStringLength/2; ++index)
{
// swap the character at "index" position with the character at "inputStringLength - index - 1" position
input[index] ^= input[inputStringLength - index - 1] ^= input[index] ^= input[inputStringLength - index - 1];
}
}
void rev_recv(std::string& s, int from, int to) {
if (from >= to) return;
rev_recv(s, from + 1, to - 1);
std::swap(s[from], s[to]);
}
void reverse(string &word) 
{
string temp = word;
if(temp.length != 0)
{
cout << temp.at(temp.length()-1);
reverse(temp.erase(temp.length()-1));
}
else
cout << "ndonen";
}

这将反向打印,而不会修改传入的原始字符串。 如果要修改原始字符串,只需删除temp变量即可。