-4

我无法弄清楚如何仅使用一个参考参数递归地反转字符串,如下面的签名。

void reverse(string &s)
{
if (s.size() == 0) //this doesn't work because the size is never changing
    return;

string new_word = s.substr(1) + s.at(0);
reverse(new_word);
}

我设法很好地返回了一个新字符串,但由于某种原因,我被这个字符串难住了。

有什么建议么?谢谢。

4

2 回答 2

2

这是一个递归版本:

void reverse( string& word )
{
    if ( word.size() <= 1 ) return;

    // Get the string without the first and the last char
    string temp = word.substr( 1, word.size() - 2 );
    // Reverse it
    reverse( temp );

    // Recompose the string
    word = word.substr( word.size() - 1 ) + temp + word[0];
}

但我真的建议您继续使用迭代版本:

// No need to explain, pretty clear
void reverse(string& word)  
{
    unsigned int end = word.size() - 1;
    for ( unsigned int i = 0; i < end; i++, end-- )
    {
        char c = word[end];
        word[end] = word[i];
        word[i] = c;
    }
}

两者都有的例子


就像建议的 syam使用 std::reverse一样:

std::reverse(str.begin(), str.end());
于 2013-08-25T22:13:16.117 回答
1

由于您已经有一个反转字符串但返回它的版本,您只需要

void reverse(string& word)  
{
    word = version_that_returns_reversed_string(word);
}
于 2013-08-25T22:00:19.537 回答