問題描述
我一直在閱讀 C++ For Everyone 一書,其中一個練習說要編寫一個函數 string reverse(string str)
,其中返回值是 str
的反函數代碼>.
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
.
有人可以寫一些基本的代碼并向我解釋一下嗎?我從昨天開始就一直盯著這個問題,無法弄清楚.我得到的最遠的是讓函數返回 str
的第一個字母(我仍然不知道它是怎么發(fā)生的)
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)
這是我得到的(發(fā)布這個問題一個小時后):
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;
}
如果我輸入Wolf",它會返回 Wol.有人幫我在這里如果我 return word
而不是 return str_copy
那么我得到一個 w
如果我 return last_letter
然后我得到一個 l
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
推薦答案
我將改為解釋遞歸算法本身.以應該產生tupni"的輸入"為例.您可以通過
I'll instead explain the recursive algorithm itself. Take the example "input" which should produce "tupni". You can reverse the string recursively by
- 如果字符串為空或單個字符,則原樣返回.
- 否則,
- 刪除第一個字符.
- 反轉剩余的字符串.
- 將上面的第一個字符添加到反轉字符串中.
- 返回新字符串.
這篇關于編寫一個遞歸函數來反轉輸入字符串的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!